Mysql中rand()的实现方式
source link: https://blogread.cn/it/article/71?f=hot1
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Mysql中rand()的实现方式
Database changed
mysql> select count(*) from test;
+----------+
| count(*) |
+----------+
| 2097152 |
+----------+
1 row in set (0.00 sec)
+--------+------+
| a | b |
+--------+------+
| 765909 | |
+--------+------+
1 row in set (8.78 sec) --用了将近9s
You cannot use a column with RAND() values in an ORDER BY clause, because ORDER BY would evaluate the column multiple times.也就是 order by rand()会去扫描多次,造成性能的下降。
先取这个表的最大值*rand(),取出这个随机值后,在进行比对。
mysql> select * from test
-> where a >= (select floor(rand() * (select max(a) from test))) order by a limit 1;
+-------+------+
| a | b |
+-------+------+
| 99275 | |
+-------+------+
1 row in set (0.00 sec) --在0.00s左右
建议继续学习:
扫一扫订阅我的微信号:IT技术博客大学习
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK