他们原来都想用PHP的实现随机,但取出多条好像要进行两次以上查询.
翻了手册,找到了下面这个语句,可以完成任务了,但效率较低
SELECT*FROMtable_nameORDERBYrand()LIMIT5;
rand在手册里是这么说的:
RAND()
RAND(N)
返回在范围0到1.0内的随机浮点值。如果一个整数参数N被指定,它被用作种子值。
mysql>selectRAND();
->0.5925
mysql>selectRAND(20);
->0.1811
mysql>selectRAND(20);
->0.1811
mysql>selectRAND();
->0.2079
mysql>selectRAND();
->0.7888
你不能在一个ORDERBY子句用RAND()值使用列,因为ORDERBY将重复计算列多次。然而在MySQL3.23中,你可以做:SELECT*FROMtable_nameORDERBYRAND(),这是有利于得到一个来自SELECT*FROMtable1,table2WHEREa=bANDc
但我试了一下,8千条记录的表,执行一次需要0.08sec,.慢了些
后来请教了google,得到如下代码
执行效率需要0.02sec.可惜的是,只有mysql4.1.*以上才支持这样的子查询.
下面是其它网友的补充: select id from zhyx_items order by rand() 这样效率太低了 优化sql语句之后:
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;
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;