quick selection of a random row from a large table in mysql

前端 未结 24 2036
旧时难觅i
旧时难觅i 2020-11-22 09:30

What is a fast way to select a random row from a large mysql table?

I\'m working in php, but I\'m interested in any solution even if it\'s in another language.

24条回答
  •  不要未来只要你来
    2020-11-22 09:48

    In my case my table has an id as primary key, auto-increment with no gaps, so I can use COUNT(*) or MAX(id) to get the number of rows.

    I made this script to test 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

    Answer with the order method:

    SELECT FLOOR(RAND() * (
        SELECT id FROM tbl ORDER BY id DESC LIMIT 1
    )) n FROM tbl LIMIT 1
    
    ...
    SELECT * FROM tbl WHERE id = $result;
    

提交回复
热议问题