Conditional sorting in MySQL?

前端 未结 2 1848
长情又很酷
长情又很酷 2021-01-21 03:18

I have \"tasks\" table with 3 fields:

  1. date
  2. priority (0,1,2)
  3. done (0,1)

What I am trying to achieve is with the whole table sorted

2条回答
  •  孤独总比滥情好
    2021-01-21 04:07

    You could try ORDER BY (done asc, aux desc) where aux is computed with a CASE to yield either priority or date based on the value of done (you may have to cast them to the same type to fit in the same expression, e.g. cast the date to a suitable integer day number).

    For example:

    SELECT * FROM tab
    ORDER BY done desc,
             case done
                 when 0 then prio 
                 else to_days(thedate)
             end desc;
    

提交回复
热议问题