问题
I have many records with a featured? attribute.
I would like to query all, group them in featured and non-featured and if possible random them in between their groups (random and show the featured ones, then random the rest).
Any idea how to do this on ActiveRecord?
回答1:
Use rand()
MySQL
SELECT * FROM <TABLE_NAME> ORDER BY featured?, rand()
RAILS 3
ModelName.order("featured, rand()")
For Ex:-
id featured
1 true
2 false
3 false
4 true
5 false
6 true
i want all the featured with value true first and then false, however order of the records withing the true and false group should be random
So my code will be
User.order("featured DESC, rand()")
and generated o/p is (Note:- order of the records between the group true/false can be changed)
id featured
4 true
6 true
1 true
5 false
3 false
2 false
来源:https://stackoverflow.com/questions/12524311/how-to-order-results-by-an-existing-boolean-attribute-first