MySQL select 10 random rows from 600K rows fast

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

    I've looked through all of the answers, and I don't think anyone mentions this possibility at all, and I'm not sure why.

    If you want utmost simplicity and speed, at a minor cost, then to me it seems to make sense to store a random number against each row in the DB. Just create an extra column, random_number, and set it's default to RAND(). Create an index on this column.

    Then when you want to retrieve a row generate a random number in your code (PHP, Perl, whatever) and compare that to the column.

    SELECT FROM tbl WHERE random_number >= :random LIMIT 1
    

    I guess although it's very neat for a single row, for ten rows like the OP asked you'd have to call it ten separate times (or come up with a clever tweak that escapes me immediately)

提交回复
热议问题