核心查找数据表代码:
select * from 表名 order by rand( ) limit 1; //此处的1就是取出数据的条数
但这样取数据网上有人说效率非常差的,那么要如何改进呢
搜索Google,网上基本上都是查询max(id) * rand()来随机获取数据。
SELECT * FROM `table` AS t1 JOIN (SELECT ROUND(RAND() * (SELECT MAX(id) FROM `table`)) AS id) AS t2 WHERE t1.id >= t2.id ORDER BY t1.id ASC LIMIT 5;
但是这样获得的是5条连续的记录。解决办法只能是每次查询一条,查询5次,但这个又不能满足我的要求了,我要一次找几条
高效写法
SELECT * FROM user WHERE userId >= ((SELECT MAX(userId) FROM user )-(SELECT MIN(userId) FROM user )) * RAND() + (SELECT MIN(userId) FROM user ) LIMIT 5