如何在数据库随机取N条数据

carmon 2002-10-25 01:14:20
我想到的是先取出所有行集,在rs.next()的时候 随机选取

不知道有没有SQL可以直接随机在数据库里选取N(是定值)条数据,不考虑字段匹配的方法
...全文
110 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
lizongqi 2003-04-28
  • 打赏
  • 举报
回复
uuuuuuup
carmon 2002-10-30
  • 打赏
  • 举报
回复
分已给出,谢谢 各位~
leimin 2002-10-30
  • 打赏
  • 举报
回复
其实j9988(j9988) 的方法也是比较好的.不过效率没有我的高.
leimin 2002-10-30
  • 打赏
  • 举报
回复
用我的方法引该可以满足你的要求.通过一个TEMPTABLE长生RANDOM()的SEED,在和原来的表关联查询.(这是MS推荐的方法!)给分吧!

use pubs
go
set nocount on
begin tran

select au_id,cast( null as float) as rnd into #RndAuthors
from Authors(TABLOCK SERIALIZABLE)
--SELECT * FROM #RndAuthors
create clustered index idx_ci_au_id on #RndAuthors(au_id)

declare @key as varchar(11)
select @key=min(au_id) from #RndAuthors

/*create a loop that iterates through all the key values,and
for each key,invokes the RAND() function with no input,update
the float column with the random value generated.*/

while @key is not null
begin
update #RndAuthors set rnd=rand() where au_id=@key
select @key=min(au_id) from #RndAuthors where au_id>@key
end
--select * from #RndAuthors
set rowcount 10

select a.* from authors as a join #RndAuthors as R
on a.au_id=R.au_id
order by rnd


drop table #RndAuthors
commit tran

j9988 2002-10-29
  • 打赏
  • 举报
回复
你的用法不对:
select * from (
Select top n * from tablename order by newid()
) a order by 某字段
carmon 2002-10-29
  • 打赏
  • 举报
回复
newid()是用于创建 uniqueidentifier 类型的唯一值

supsuccess(火气不小):你可以试试
Select top n * from tablename order by 某字段,newid()
连续做几次会发现取到的结果集都是一样的
我需要的是‘每次’取到的都是随机的 :)

hjhing(winding) 的方法不错,但是有一个问题就是不能保证选取数据的比例,可能某次会取到很多数据,某次会取到比较少的数据

CrazyFor(Fan) 的方法我一会试试,吃饭了

下午散分各位~
奇遇 2002-10-29
  • 打赏
  • 举报
回复
old problem ,agree with j9988
supsuccess 2002-10-28
  • 打赏
  • 举报
回复
楼主:
Select top n * from tablename order by newid()
肯定能达到你的要求,看来你根本就没有执行此语句,只是凭自己的感觉就把它否定了:)
CrazyFor 2002-10-28
  • 打赏
  • 举报
回复
declare @conut int,@IdStr varchar (8000),@intX int ,@ShoeCount int
select @ShoeCount=20
select @conut=(select count(*) from Table)
drop table #table1
select IDENTITY(int,1, 1) as iid,*
into #table1
from Table
select @intX=0
while @intX<@ShoeCount
Begin
select @IdStr=@IdStr+''''+cast(cast(rand()*@conut as int)as varchar)+''''
select @intX=@intX+1
if @intX<@ShoeCount select @IdStr=@IdStr+','
End

select * from #table1 where Iid in (@IdStr)
carmon 2002-10-28
  • 打赏
  • 举报
回复
Select top n * from table order by newid() ,如果做这样的操作X次,那每次所得到的行集都是一样的,我的目的是每次取不同的行集(总数量是相同的)
lyyrw 2002-10-25
  • 打赏
  • 举报
回复
我的方法和Suncanoe(小舟) 的一样,这样就可以了。
hjhing 2002-10-25
  • 打赏
  • 举报
回复
select top 200 IDENTITY(int,1,1) as rid,* into #jr from yourtable
declare @rindex int
set @rindex= ceiling( rand()*10)
select top 10 * from #jr where rid % @rindex =0
drop table #jr
Suncanoe 2002-10-25
  • 打赏
  • 举报
回复
Select top n * from table order by newid()
coo_key 2002-10-25
  • 打赏
  • 举报
回复
使用top n 和newid()

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧