从数据库中随机取出N条记录的方法,Sql Server和Access中

Sql Server中如下取,很简单,newid()即可
select top N * from TABLE order by newid()

Access中用如下语句虽说可以取到随机的记录,但每次取的都相同,故如下语句用处不大:
select top N * from TABLE order by RND(id)
id一个数字列,最好是主键,其它列也可,如:RND(len(username))

但可以用如下的order by使每次取的记录都不相同:
select top N * from TABLE order by RND(-(随机数-id))
RND()里面必须是负值,随机数可以自己用程序生成,如:
select top 10 * from js_FaceCat a order by Rnd(-("+new System.Random().Next(666666)+"+a.catID))

花了一上午找资料看access如何简单的取随机记录,但没有搞明白为什么要如此,凑合用了。

Leave a comment

0 Comments.

Leave a Reply


[ Ctrl + Enter ]


Verify Code   If you cannot see the CheckCode image,please refresh the page again!