gpt4 book ai didi

mysql - SQL 查询中的 RAND() 是如何工作的

转载 作者:可可西里 更新时间:2023-11-01 08:10:01 27 4
gpt4 key购买 nike

下面的查询实际上是如何工作的?

SELECT * FROM t ORDER BY RAND() LIMIT 1;

它是否首先对源数据库中的所有 记录进行排序,然后截断它以获得 1 行?

最佳答案

这个问题与 LIMIT 查询优化有关,而不是 RAND() 是如何工作的。

来自 manual (大胆强调我的):

If you combine LIMIT row_count with ORDER BY, MySQL ends the sorting as soon as it has found the first row_count rows of the sorted result, rather than sorting the entire result.

If ordering is done by using an index, this is very fast. If a filesort must be done, all rows that match the query without the LIMIT clause are selected, and most or all of them are sorted, before the first row_count are found. After the initial rows have been found, MySQL does not sort any remainder of the result set.

关于mysql - SQL 查询中的 RAND() 是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39189756/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com