09

关于随机抽取order By Rand()的效率问题和改进写法!

最近由于需要大概研究了一下MYSQL的随机抽取实现方法。

举个例子,要从tablename表中随机提取一条记录,大家一般的写法就是 SELECT * FROM tablename ORDER BY RAND() LIMIT 1

但是,后来我查了一下MYSQL的官方手册,里面针对RAND()有如下提示:

You can’t use a column with RAND() values in an ORDER BY clause, because ORDER BY would evaluate the column multiple times. In MySQL Version 3.23, you can, however, do: SELECT * FROM table_name ORDER BY RAND()

大概意思就是,在ORDER BY从句里面不能使用RAND()函数,因为这样会导致数据列被多次扫描。但是在MYSQL 3.23版本中,仍然可以通过ORDER BY RAND()来实现随机。

继续阅读全文