Saturday, July 26, 2008

提高mysql随机查询的效率


  1. 基本使用:
    SELECT * FROM `table` ORDER BY RAND() LIMIT 0,10;
    但是在ORDER BY后面用到RAND(),查询速度非常慢.

  2. MAX()*RAND()提高效率
    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;

  3. JOIN
    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;



No comments:

Post a Comment