How to quickly SELECT 3 random records from a 30k MySQL table with a where filter by a single query?

后端 未结 6 1882
生来不讨喜
生来不讨喜 2020-12-14 02:38

Well, this is a very old question never gotten real solution. We want 3 random rows from a table with about 30k records. The table is not so big in point of view MySQL, but

6条回答
  •  -上瘾入骨i
    2020-12-14 03:09

    SELECT Products.ID, Products.Name
    FROM Products
    INNER JOIN (SELECT (RAND() * (SELECT MAX(ID) FROM Products)) AS ID) AS t ON Products.ID     >= t.ID
    WHERE (Products.HasImages=1)
    ORDER BY Products.ID ASC
    LIMIT 3;
    

    Of course the above is given "near" contiguous records you are feeding it the same ID every time without much regard to the seed of the rand function.

    This should give more "randomness"

    SELECT Products.ID, Products.Name
    FROM Products
    INNER JOIN (SELECT (ROUND((RAND() * (max-min))+min)) AS ID) AS t ON Products.ID     >= t.ID
    WHERE (Products.HasImages=1)
    ORDER BY Products.ID ASC
    LIMIT 3;
    

    Where max and min are two values you choose, lets say for example sake:

    max = select max(id)
    min = 225
    

提交回复
热议问题