SQL 以随机顺序返回行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1117761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Return rows in random order
提问by Arsen Mkrtchyan
Is it possible to write SQL query that returns table rows in random order every time the query run?
是否可以编写每次查询运行时以随机顺序返回表行的 SQL 查询?
回答by Dave Barker
SELECT * FROM table
ORDER BY NEWID()
回答by Alec Smart
回答by devstuff
The usual method is to use the NEWID() function, which generates a unique GUID. So,
通常的方法是使用 NEWID() 函数,它会生成一个唯一的 GUID。所以,
SELECT * FROM dbo.Foo ORDER BY NEWID();
回答by nilamo
To be efficient, and random, it might be best to have two different queries.
为了高效和随机,最好有两个不同的查询。
Something like...
就像是...
SELECT table_id FROM table
SELECT table_id FROM 表
Then, in your chosen language, pick a random id, then pull that row's data.
然后,在您选择的语言中,选择一个随机 ID,然后提取该行的数据。
SELECT * FROM table WHERE table_id = $rand_id
SELECT * FROM table WHERE table_id = $rand_id
But that's not really a good idea if you're expecting to have lots of rows in the table. It would be better if you put some kind of limit on what you randomly select from. For publications, maybe randomly pick from only items posted within the last year.
但是,如果您希望表中有很多行,这并不是一个好主意。如果您对随机选择的内容设置某种限制会更好。对于出版物,可能仅从去年发布的项目中随机选择。
回答by PinoyDev
回答by Dan Both
SQL Server / MS Access Syntax:
SQL Server / MS 访问语法:
SELECT TOP 1 * FROM table_name ORDER BY RAND()
MySQL Syntax:
MySQL 语法:
SELECT * FROM table_name ORDER BY RAND() LIMIT 1