MySQL select 10 random rows from 600K rows fast

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

    This is super fast and is 100% random even if you have gaps.

    1. Count the number x of rows that you have available SELECT COUNT(*) as rows FROM TABLE
    2. Pick 10 distinct random numbers a_1,a_2,...,a_10 between 0 and x
    3. Query your rows like this: SELECT * FROM TABLE LIMIT 1 offset a_i for i=1,...,10

    I found this hack in the book SQL Antipatterns from Bill Karwin.

提交回复
热议问题