【问题标题】:How to sort a table by checking the value of a specific field and then sorting the others differently [duplicate]如何通过检查特定字段的值然后以不同方式对其他字段进行排序来对表进行排序[重复]
【发布时间】:2018-04-13 00:39:30
【问题描述】:

我的应用中有Notifications 的模型,其中一个字段是event_type,用于生成通知。

使用我们 API 的移动客户端希望通过发出单个请求以特定方式返回的通知。

他们希望所有带有event_typeconnection_invite 的通知首先返回,然后所有其他event_types 的通知按created_at desc 排序。

所以Notifications的集合喜欢:

[
 #<Notification:0x007f id: 1, event_type: "content_assigned", created_at: Sat, 21 Oct 2017 21:10:56 UTC +00:00, updated_at: Sat, 21 Oct 2017 21:16:14 UTC +00:00>,
 #<Notification:0x007f id: 1, event_type: "connection_invite", created_at: Sun, 22 Oct 2017 21:10:56 UTC +00:00, updated_at: Sun, 22 Oct 2017 21:16:14 UTC +00:00>,
 #<Notification:0x007f id: 3, event_type: "post_created", created_at: Sun, 22 Oct 2017 21:10:56 UTC +00:00, updated_at: Sun, 22 Oct 2017 21:16:14 UTC +00:00>,
 #<Notification:0x007f id: 4, event_type: "connection_invite", created_at: Sat, 21 Oct 2017 21:10:56 UTC +00:00, updated_at: Sat, 21 Oct 2017 21:16:14 UTC +00:00>
]

将返回排序如下的集合:

[
 #<Notification:0x007f id: 4, event_type: "connection_invite", created_at: Sat, 21 Oct 2017 21:10:56 UTC +00:00, updated_at: Sat, 21 Oct 2017 21:16:14 UTC +00:00>
 #<Notification:0x007f id: 2, event_type: "connection_invite", created_at: Fri, 20 Oct 2017 21:10:56 UTC +00:00, updated_at: Fri, 20 Oct 2017 21:16:14 UTC +00:00>,
 #<Notification:0x007f id: 3, event_type: "post_created", created_at: Sun, 22 Oct 2017 21:10:56 UTC +00:00, updated_at: Sun, 22 Oct 2017 21:16:14 UTC +00:00>,
 #<Notification:0x007f id: 1, event_type: "content_assigned", created_at: Sat, 21 Oct 2017 21:10:56 UTC +00:00, updated_at: Sat, 21 Oct 2017 21:16:14 UTC +00:00>,
]

【问题讨论】:

    标签: sql ruby-on-rails postgresql sorting ruby-on-rails-4


    【解决方案1】:

    只需将排序顺序放入查询中即可:

    order by ( (event_type = 'connection_invite')::int desc),
             created_at desc
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-19
      • 2020-04-29
      • 1970-01-01
      • 2013-04-20
      • 1970-01-01
      • 2017-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多