MySQL使用查询随机条数数据的方法,如MySQL查询随机10条数据。

方法1,简单易懂,但是查询效率很慢,适用于表中数据较少的情况。


SELECT * FROM `table` ORDER BY RAND() limit 10

方法2,语句复杂,但是查询效率很快,适用于表中数据较多的情况。


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 10;