MySQL select 10 random rows from 600K rows fast

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

    Another simple solution would be ranking the rows and fetch one of them randomly and with this solution you won't need to have any 'Id' based column in the table.

    SELECT d.* FROM (
    SELECT  t.*,  @rownum := @rownum + 1 AS rank
    FROM mytable AS t,
        (SELECT @rownum := 0) AS r,
        (SELECT @cnt := (SELECT RAND() * (SELECT COUNT(*) FROM mytable))) AS n
    ) d WHERE rank >= @cnt LIMIT 10;
    

    You can change the limit value as per your need to access as many rows as you want but that would mostly be consecutive values.

    However, if you don't want consecutive random values then you can fetch a bigger sample and select randomly from it. something like ...

    SELECT * FROM (
    SELECT d.* FROM (
        SELECT  c.*,  @rownum := @rownum + 1 AS rank
        FROM buildbrain.`commits` AS c,
            (SELECT @rownum := 0) AS r,
            (SELECT @cnt := (SELECT RAND() * (SELECT COUNT(*) FROM buildbrain.`commits`))) AS rnd
    ) d 
    WHERE rank >= @cnt LIMIT 10000 
    ) t ORDER BY RAND() LIMIT 10;
    

提交回复
热议问题