2B青年的写法:
SELECT * FROM tablename ORDER BY RAND() LIMIT 1
据MYSQL手册上介绍:在ORDER BY 语句中,不能使用一个带有RAND() 值的列,原因是 ORDER BY 会计算列的多重时间,但是 仍然可以通过ORDER BY RAND()来实现随机,数据库量大的时候,执行效率超低。
文艺青年的写法:
1、
SELECT *
FROM `table` AS t1
JOIN (SELECT ROUND(RAND() * ((SELECT MAX(id) FROM `table`)-(SELECT MIN(id) FROM `table`))+(SELECT MIN(id)
FROM `table`)) AS id) AS t2
WHERE t1.id >= t2.id
ORDER BY t1.id LIMIT 1;
2、
SELECT * FROM `table`
WHERE id >= (SELECT floor( RAND() * ((SELECT MAX(id) FROM `table`)-(SELECT MIN(id) FROM `table`)) + (SELECT MIN(id) FROM `table`)))
ORDER BY id LIMIT 1;
最后在php中对这两个语句进行分别查询10次,
后者花费时间 0.147433 秒
前者花费时间 0.015130 秒
看来采用JOIN的语法比直接在WHERE中使用函数效率还要高很多。
参考:http://www.cnblogs.com/phper7/archive/2010/05/26/1744063.html