MySQL取出随机数据
他们原来都想用php的实现随机,但取出多条好像要进行两次以上查询.
翻了手册,找到了下面这个语句,可以完成任务了,但效率较低
select * from table_name order by rand() limit 5;
rand在手册里是这么说的:
rand()
rand(n)
返回在范围0到1.0内的随机浮点值。如果一个整数参数n被指定,它被用作种子值。
mysql> select rand();
-> 0.5925
mysql> select rand(20);
-> 0.1811
mysql> select rand(20);
-> 0.1811
mysql> select rand();
-> 0.2079
mysql> select rand();
-> 0.7888
你不能在一个order by子句用rand()值使用列,因为order by将重复计算列多次。然而在mysql3.23中,你可以做: select * from table_name order by rand(),这是有利于得到一个来自select * from table1,table2 where a=b and c<d order by rand() limit 1000的集合的随机样本。注意在一个where子句里的一个rand()将在每次where被执行时重新评估。
但我试了一下,8千条记录的表,执行一次需要0.08 sec,.慢了些
后来请教了google,得到如下代码
select * from table_name as r1 join (select round(rand() * (select max(id) from table_name)) as id) as r2 where r1.id >= r2.id order by r1.id asc limit 5;
执行效率需要0.02 sec.可惜的是,只有mysql 4.1.*以上才支持这样的子查询.
下面是其它网友的补充:
select id from zhyx_items order by rand() 这样效率太低了
优化sql语句之后:
select t1.id from zhyx_items as t1 join (select round(rand() * ((select max(id) from zhyx_items)-(select min(id) from zhyx_items))+ (select min(id) from zhyx_items)) as id) as t2 where t1.id >= t2.id order by t1.id limit 0,5;