MySQL select 10 random rows from 600K rows fast

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

    You can easily use a random offset with a limit

    PREPARE stm from 'select * from table limit 10 offset ?';
    SET @total = (select count(*) from table);
    SET @_offset = FLOOR(RAND() * @total);
    EXECUTE stm using @_offset;
    

    You can also apply a where clause like so

    PREPARE stm from 'select * from table where available=true limit 10 offset ?';
    SET @total = (select count(*) from table where available=true);
    SET @_offset = FLOOR(RAND() * @total);
    EXECUTE stm using @_offset;
    

    Tested on 600,000 rows (700MB) table query execution took ~0.016sec HDD drive.

    EDIT: The offset might take a value close to the end of the table, which will result in the select statement returning less rows (or maybe only 1 row), to avoid this we can check the offset again after declaring it, like so

    SET @rows_count = 10;
    PREPARE stm from "select * from table where available=true limit ? offset ?";
    SET @total = (select count(*) from table where available=true);
    SET @_offset = FLOOR(RAND() * @total);
    SET @_offset = (SELECT IF(@total-@_offset<@rows_count,@_offset-@rows_count,@_offset));
    SET @_offset = (SELECT IF(@_offset<0,0,@_offset));
    EXECUTE stm using @rows_count,@_offset;
    

提交回复
热议问题