MySQL select 10 random rows from 600K rows fast

后端 未结 26 2984
粉色の甜心
粉色の甜心 2020-11-21 05:06

How can I best write a query that selects 10 rows randomly from a total of 600k?

26条回答
  •  心在旅途
    2020-11-21 05:31

    I think here is a simple and yet faster way, I tested it on the live server in comparison with a few above answer and it was faster.

     SELECT * FROM `table_name` WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM `table_name` ) ORDER BY id LIMIT 30; 
    

    //Took 0.0014secs against a table of 130 rows

    SELECT * FROM `table_name` WHERE 1 ORDER BY RAND() LIMIT 30
    

    //Took 0.0042secs against a table of 130 rows

     SELECT name
    FROM random AS r1 JOIN
       (SELECT CEIL(RAND() *
                     (SELECT MAX(id)
                        FROM random)) AS id)
        AS r2
    WHERE r1.id >= r2.id
    ORDER BY r1.id ASC
    LIMIT 30
    

    //Took 0.0040secs against a table of 130 rows

提交回复
热议问题