如何随机取记录?(MSSQL、Access、MySql)
1、数据量少的时候可以使用sql自带的newid()函数 select top 7 from table order by newid() select top 5 a.columName from (select distinct columName from tableName) a order by newid()
2、数据量大则不适合用上述方法了,简单算法: 统计表里所有的数据 N,然后返回一个小于N的随机数,再选择一条ID大于N就行了! SELECT TOP 10 * FROM TB1 WHERE (id > CAST(FLOOR(RAND() * (SELECT COUNT(id) FROM [ TB1])) AS int))
随机提取10条记录的例子:
Sql server:
select top 10 * from 表 order by newid()
Access:
SELECT top 10 * FROM 表 ORDER BY Rnd(id)
Rnd(id) 其中的id是自动编号字段,可以利用其他任何数值来完成
比如用姓名字段(UserName)
SELECT top 10 * FROM 表 ORDER BY Rnd(len(UserName))
MySql:
Select * From 表 Order By rand() Limit 10 ==========================================================
ACCESS可以用RND函数结合ASP中的RND函数来实现随机抽取。 <% ... Randomize strSQL = "SELECT TOP 1 字段列表 FROM 表名 ORDER BY RND(-(编号字段)*" & RND() & ")" ... %>
===============================================
要产生指定范围的随机整数,请使用以下公式: Int((upperbound - lowerbound + 1) * Rnd + lowerbound) 这里, upperbound 是此范围的上界,而 lowerbound 是此范围内的下界
==========================================================
随机提取10条记录的例子:
Sql server:
select top 10 * from 表 order by newid()
Access:
SELECT top 10 * FROM 表 ORDER BY Rnd(id)
Rnd(id) 其中的id是自动编号字段,可以利用其他任何数值来完成
比如用姓名字段(UserName)
SELECT top 10 * FROM 表 ORDER BY Rnd(len(UserName))
MySql:
Select * From 表 Order By rand() Limit 10
========================================================
select top 4 * from DataTable order by rnd(-(id+rnd()))
=====================================================
ASP&Access随机读取某段数据
在网上也搜索了很多,分享下我的方法... 以下是源代码:
Randomize(Timer()) SQL = "SELECT TOP 100 ID FROM table1 ORDER BY Rnd(-(ID + " & Int((10000 * Rnd) + 1) & "))" Set RS = Server.CreateObject("ADODB.RecordSet") RS.Open SQL,Conn,1,1 If Not RS.EOF Then RS.MoveFirst For I = 1 To RS.RecordCount Response.Write RS(0) & "
" RS.MoveNext Next End If RS.Close Set RS = Nothing