Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我需要获取一个字段值为 的随机status记录2。
status
2
如果您担心速度,这可能会更快:
Model.where(status: 2).offset(rand(Model.where(status: 2).count)).first
真正的黑客方法是:
Model.where(:status => 2).order('RAND()').first
请注意,ORDER BY RAND()在大桌子上可能会非常慢,但对于小桌子来说没问题。
ORDER BY RAND()