欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

order by newid() 各种数据库随机查询的方法

程序员文章站 2023-11-20 20:48:46
sql server:复制代码 代码如下:select top n * from table order by newid()   view plain...

sql server:

复制代码 代码如下:

select top n * from table order by newid()  
view plaincopy to clipboardprint?
select top n * from table order by newid()

select top n * from table order by newid()


newid()函数将创建一个 uniqueidentifier 类型的唯一值。上面的语句实现效果是从table中随机读取n条记录。

access:

复制代码 代码如下:

select top n * from table order by rnd(id)   
view plaincopy to clipboardprint?
select top n * from table order by rnd(id) 

select top n * from table order by rnd(id)


rnd(id) 其中的id是自动编号字段,可以利用其他任何数值来完成,比如用姓名字段(username)
复制代码 代码如下:

select top n * from table order by rnd(len(username))  
view plaincopy to clipboardprint?
select top n * from table order by rnd(len(username))

select top n * from table order by rnd(len(username))


mysql:
复制代码 代码如下:

select * from table order by rand() limit 10  
view plaincopy to clipboardprint?
select * from table order by rand() limit 10

select * from table order by rand() limit 10

postgresql:

复制代码 代码如下:

select * from glxt022 order by random() limit 5  
view plaincopy to clipboardprint?
select * from glxt022 order by random() limit 5