php MySQL ORDER BY rand(),名称 ASC
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2882647/
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
MySQL ORDER BY rand(), name ASC
提问by Josh K
I would like to take a database of say, 1000 users and select 20 random ones (ORDER BY rand(),LIMIT 20) then order the resulting set by the names. I came up with the following query which is notworking like I hoped.
我想以一个数据库为例,1000 个用户并选择 20 个随机的(ORDER BY rand(), LIMIT 20),然后按名称对结果集进行排序。我想出了这是下面的查询不工作像我希望的。
SELECT * FROM users WHERE 1 ORDER BY rand(), name ASC LIMIT 20
SELECT * FROM users WHERE 1 ORDER BY rand(), name ASC LIMIT 20
回答by Mark Byers
Use a subquery:
使用子查询:
SELECT * FROM
(
SELECT * FROM users ORDER BY rand() LIMIT 20
) T1
ORDER BY name
The inner query selects 20 users at random and the outer query orders the selected users by name.
内部查询随机选择 20 个用户,外部查询按名称对所选用户进行排序。
回答by ircmaxell
Beware of ORDER BY RAND() because of performance and results. Check this article out: http://jan.kneschke.de/projects/mysql/order-by-rand/
由于性能和结果,请注意 ORDER BY RAND()。看看这篇文章:http: //jan.kneschke.de/projects/mysql/order-by-rand/
回答by Siqi Lin
Instead of using a subquery, you could use two separate queries, one to get the number of rows and the other to select the random rows.
您可以不使用子查询,而是使用两个单独的查询,一个用于获取行数,另一个用于选择随机行。
SELECT COUNT(id) FROM users; #id is the primary key
Then, get a random twenty rows.
然后,得到一个随机的二十行。
$start_row = mt_rand(0, $total_rows - 20);
The final query:
最后查询:
SELECT * FROM users ORDER BY name ASC LIMIT $start_row, 20;
回答by Quassnoi
SELECT *
FROM (
SELECT *
FROM users
WHERE 1
ORDER BY
rand()
LIMIT 20
) q
ORDER BY
name
回答by Alexander Konstantinov
Use a subquery:
使用子查询:
SELECT * FROM (
SELECT * FROM users ORDER BY RAND() LIMIT 20
) u
ORDER BY name
or a join to itself:
或连接到自身:
SELECT * FROM users u1
INNER JOIN (
SELECT id FROM users ORDER BY RAND() LIMIT 20
) u2 USING(id)
ORDER BY u1.name

