简体   繁体   中英

MySQL ordering by grouped date ranges

I have a model with the following four scopes:

scope :active, -> { where("start_at <= '#{Time.now.utc}' AND end_at > '#{Time.now.utc}'") }
scope :ended, -> { where("end_at < '#{Time.now.utc}'") }
scope :coming_soon, -> { where("start_at > '#{Time.now.utc}' AND start_at < '#{Time.now.utc+6.hours}'") }

I want to be able to do something like (pseudocode, just trying to give an idea):

Model.all.order(active, coming_soon, ended)

The result would be all rows from that table, sorted by rows meeting the active constraints first, followed by the ones meeting the coming_soon constraint, and finally all the ones meeting the ended constraints.

I added the following scope and it seems to have solved my problem:

scope :time_sorted, -> { 
    select("events.*, CASE 
      WHEN start_at <= '#{Time.now.utc}' AND end_at > '#{Time.now.utc}' THEN 1
      WHEN end_at < '#{Time.now.utc}' THEN 2
      WHEN start_at > '#{Time.now.utc}' AND start_at < '#{Time.now.utc+6.hours}' THEN 3 ELSE 4
      END AS formula")
    .order("formula ASC")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM