MySQL select 10 random rows from 600K rows fast

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

    Here is a game changer that may be helpfully for many;

    I have a table with 200k rows, with sequential id's, I needed to pick N random rows, so I opt to generate random values based in the biggest ID in the table, I created this script to find out which is the fastest operation:

    logTime();
    query("SELECT COUNT(id) FROM tbl");
    logTime();
    query("SELECT MAX(id) FROM tbl");
    logTime();
    query("SELECT id FROM tbl ORDER BY id DESC LIMIT 1");
    logTime();
    

    The results are:

    • Count: 36.8418693542479 ms
    • Max: 0.241041183472 ms
    • Order: 0.216960906982 ms

    Based in this results, order desc is the fastest operation to get the max id,
    Here is my answer to the question:

    SELECT GROUP_CONCAT(n SEPARATOR ',') g FROM (
        SELECT FLOOR(RAND() * (
            SELECT id FROM tbl ORDER BY id DESC LIMIT 1
        )) n FROM tbl LIMIT 10) a
    
    ...
    SELECT * FROM tbl WHERE id IN ($result);
    

    FYI: To get 10 random rows from a 200k table, it took me 1.78 ms (including all the operations in the php side)

提交回复
热议问题