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

前端 未结 24 2022
旧时难觅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:47

    I'm a bit new to SQL but how about generating a random number in PHP and using

    SELECT * FROM the_table WHERE primary_key >= $randNr
    

    this doesn't solve the problem with holes in the table.

    But here's a twist on lassevks suggestion:

    SELECT primary_key FROM the_table
    

    Use mysql_num_rows() in PHP create a random number based on the above result:

    SELECT * FROM the_table WHERE primary_key = rand_number
    

    On a side note just how slow is SELECT * FROM the_table:
    Creating a random number based on mysql_num_rows() and then moving the data pointer to that point mysql_data_seek(). Just how slow will this be on large tables with say a million rows?

提交回复
热议问题