<span style="color: rgb(70, 70, 70); font-family: Verdana, 'BitStream vera Sans', Helvetica, sans-serif; font-size: 13px; line-height: 20.799999237060547px;">从数据表随机获取N条数据记录的方法有很多,其中最简单的莫过于SELECT * FROM `table` WHERE 1 ORDER BY rand() LIMIT N 这个语句得好处在于简单,但前提条件是查询的结果集必须小于5W记录集的情况下方可使用,若数据结果集超过了5W,其查询出来的速度将非常的耗资源。</span>
SELECT * FROM `baidu` AS k1 JOIN (
SELECT ROUND( RAND( ) * (
(SELECT MAX( id ) FROM `baidu` ) - (SELECT MIN( id ) FROM `baidu` ) ) +
(SELECT MIN( id ) FROM `baidu` )) AS id
) AS k2
WHERE k1.id >= k2.id LIMIT 10
0.0445秒 连续记录
SELECT * FROM `baidu`
WHERE id >= (floor(RAND() * (SELECT MAX(id) FROM `baidu`)))
ORDER BY id LIMIT 10;
0.0710 不连续
SELECT *
FROM `baidu` AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(id) FROM `baidu`)-(SELECT MIN(id) FROM `baidu`))+(SELECT MIN(id) FROM `baidu`)) AS id) AS t2
WHERE t1.id >= t2.id
ORDER BY t1.id LIMIT 10;
0.0203 连续的
SELECT * FROM `baidu`
WHERE id >= (SELECT floor( RAND() * ((SELECT MAX(id) FROM `baidu`)-(SELECT MIN(id) FROM `baidu`)) + (SELECT MIN(id) FROM `baidu`)))
ORDER BY id LIMIT 10;
0.0668 不连续
SELECT * FROM `baidu` AS k1 JOIN ( SELECT ROUND( RAND( ) * ( (SELECT MAX( id ) FROM `baidu` ) - (SELECT MIN( id ) FROM `baidu` ) ) + (SELECT MIN( id ) FROM `baidu` )) AS id