我在我的導軌模型上有一個範圍,它應該可以幫助我對對象進行排序。這是如下圖所示:ORDER BY CASE子句的作用域不能正常工作
scope :active, ->(u = nil, now = "NOW()") {
published_and_private(u).eager_load(:images)
.where("(listing = 1 AND complete = 0) OR " + # LISTING
"(online_only = 1 AND scheduled_end_time + INTERVAL 1 DAY >= #{now}) OR " + # TIMED
"(online_only = 0 AND listing = 0 AND starts_at + INTERVAL 1 DAY >= #{now})") # LIVE
.order("complete, CASE WHEN sort_index IS NOT NULL THEN sort_index " +
"WHEN scheduled_end_time IS NOT NULL THEN scheduled_end_time " +
"WHEN starts_at IS NOT NULL THEN starts_at ELSE #{now} + INTERVAL 10 YEAR END")
}
下面是從返回當查詢被運行數據庫中的數據:
select id, name, complete, sort_index, starts_at, scheduled_end_time from auctions where published = 1 ORDER BY complete, CASE WHEN sort_index IS not NULL THEN sort_index WHEN scheduled_end_time IS NOT NULL THEN scheduled_end_time WHEN starts_at IS NOT NULL THEN starts_at ELSE (NOW() + INTERVAL 10 YEAR) END;
+----+-----------------------------------+----------+------------+---------------------+---------------------+
| id | name | complete | sort_index | starts_at | scheduled_end_time |
+----+-----------------------------------+----------+------------+---------------------+---------------------+
| 21 | Listing: Mountain Cabin Estate | 0 | 1 | NULL | NULL |
| 17 | Multi-Item Online Only | 0 | 2 | 2017-08-07 06:48:00 | 2017-08-21 12:48:00 |
| 9 | Multi-item Live Auction | 0 | NULL | 2017-08-21 18:48:02 | NULL |
| 19 | Many Item LIVE Auction | 0 | NULL | 2017-08-21 18:48:02 | NULL |
| 10 | Single Item Online Only | 0 | NULL | 2017-08-07 18:48:03 | 2017-08-22 00:48:02 |
| 18 | MANY Item Timed Auction | 0 | NULL | 2017-08-07 18:48:03 | 2017-08-22 00:48:02 |
| 22 | LISTING: Multi-parcel Real Estate | 0 | NULL | NULL | NULL |
| 20 | Bad Images | 0 | 3 | 2017-08-21 14:48:00 | NULL |
| 8 | Single Item Live Auction | 1 | NULL | 2017-08-21 18:48:02 | NULL |
+----+-----------------------------------+----------+------------+---------------------+---------------------+
我的問題是,隨着3排序索引的對象是出地方,這發生在2以上的任何數字,我完全喪失了爲什麼這可能是。我期待查詢將該對象放在sort_index爲2的那個下面。
任何幫助,指導或見解都將不勝感激。
如果你想想你的BY子句順序並沒有太大的意義。你將整數與日期混合在一起。這些應該如何排序? –