想从MySQL数据库中随机取一条或者N条记录时,最好把RAND()生成随机数放在JOIN子查询中以提高效率。
SELECT id FROM table ORDER BY RAND() LIMIT n;
改造成下面这个:
SELECT id FROM table t1 JOIN (SELECT RAND() * (SELECT MAX(id) FROM table) AS nid) t2 ON t1.id > t2.nid LIMIT n;
如果想要达到完全随机,还可以改成下面这种写法:
SELECT id FROM table t1 JOIN (SELECT round(RAND() * (SELECT MAX(id) FROM table)) AS nid FROM table LIMIT n) t2 ON t1.id = t2.nid;
就可以享受在SQL中直接取得随机数了,不用再在程序中构造一串随机数去检索了。查询结果可能不全
时间: 2024-11-19 07:12:45