开发者

Random MySQL row while avoiding holes

开发者 https://www.devze.com 2022-12-20 00:03 出处:网络
I have a big MySQL users table and need to get six random rows from it (I\'m using PHP). The table has an index column that is auto incremented. The only problem is that some rows are marked as inacti

I have a big MySQL users table and need to get six random rows from it (I'm using PHP). The table has an index column that is auto incremented. The only problem is that some rows are marked as inactive, because some users have disabled their accounts or whatever. That means I can't just count the rows and then grab a random number from that range because some of them will be inactive.

How can I efficiently get a random row without using RAND() and without trying to query an inactive 开发者_JS百科user?

Thanks!


WHERE `inactive` = 0 LIMIT random_offset, 1

where random_offset is precalculated in PHP (as random from 1 to COUNT of active users). And the result consists of 6 UNIONed queries.


If you wish to avoid the very slow order by RAND() method, here are various alternatives, with various options to manage holes

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号