Conditional sorting in MySQL?

偶尔善良 提交于 2020-01-11 09:58:47

问题


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 by done flag, tasks that are not done should be sorted by priority, while tasks that are done should be sorted by date:

  1. Select * from tasks order by done asc
  2. If done=0 additionally order by priority desc
  3. If done=1 additionally order by date desc

Is it possible to do this in MySQL without unions?

Thanks.


回答1:


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;



回答2:


Taken from Alex Martelli just shortened a bit with IF() and fixed the ASC/DESC ordering

SELECT * FROM tab
ORDER BY done ASC, IF(done, to_days(thedate), prio) DESC;


来源:https://stackoverflow.com/questions/1084362/conditional-sorting-in-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!