MySQL select 10 random rows from 600K rows fast

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

    From book :

    Choose a Random Row Using an Offset

    Still another technique that avoids problems found in the preceding alternatives is to count the rows in the data set and return a random number between 0 and the count. Then use this number as an offset when querying the data set

    $rand = "SELECT ROUND(RAND() * (SELECT COUNT(*) FROM Bugs))";
    $offset = $pdo->query($rand)->fetch(PDO::FETCH_ASSOC);
    $sql = "SELECT * FROM Bugs LIMIT 1 OFFSET :offset";
    $stmt = $pdo->prepare($sql);
    $stmt->execute( $offset );
    $rand_bug = $stmt->fetch();
    

    Use this solution when you can’t assume contiguous key values and you need to make sure each row has an even chance of being selected.

提交回复
热议问题