quick selection of a random row from a large table in mysql

前端 未结 24 2028
旧时难觅i
旧时难觅i 2020-11-22 09:30

What is a fast way to select a random row from a large mysql table?

I\'m working in php, but I\'m interested in any solution even if it\'s in another language.

24条回答
  •  耶瑟儿~
    2020-11-22 09:54

    I ran into the problem where my IDs were not sequential. What I came up with this.

    SELECT * FROM products WHERE RAND()<=(5/(SELECT COUNT(*) FROM products)) LIMIT 1
    

    The rows returned are approximately 5, but I limit it to 1.

    If you want to add another WHERE clause it becomes a bit more interesting. Say you want to search for products on discount.

    SELECT * FROM products WHERE RAND()<=(100/(SELECT COUNT(*) FROM pt_products)) AND discount<.2 LIMIT 1
    

    What you have to do is make sure you are returning enough result which is why I have it set to 100. Having a WHERE discount<.2 clause in the subquery was 10x slower, so it's better to return more results and limit.

提交回复
热议问题