MySQL select 10 random rows from 600K rows fast

后端 未结 26 2922
粉色の甜心
粉色の甜心 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:29

    If you want one random record (no matter if there are gapes between ids):

    PREPARE stmt FROM 'SELECT * FROM `table_name` LIMIT 1 OFFSET ?';
    SET @count = (SELECT
            FLOOR(RAND() * COUNT(*))
        FROM `table_name`);
    
    EXECUTE stmt USING @count;
    

    Source: https://www.warpconduit.net/2011/03/23/selecting-a-random-record-using-mysql-benchmark-results/#comment-1266

提交回复
热议问题