How to order results by an existing boolean attribute first

情到浓时终转凉″ 提交于 2019-12-11 09:45:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!