本文介绍了如何首先通过现有的布尔属性对结果进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有许多具有功能?属性的记录。

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).

有人知道如何在ActiveRecord上执行此操作吗?

Any idea how to do this on ActiveRecord?

推荐答案

使用

MySQL

SELECT * FROM <TABLE_NAME> ORDER BY featured?, rand()

铁路3

ModelName.order("featured, rand()")

对于Ex:-

id    featured
1      true
2      false
3      false
4      true
5      false
6      true

i想要所有具有true值然后为false的特征,但是带有true和false组的记录的顺序应该是随机的

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

所以我的代码将是

User.order("featured DESC, rand()")

且生成的o / p是(注意:-组之间的记录的正确/错误可以更改)

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

这篇关于如何首先通过现有的布尔属性对结果进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 03:02