What does it happen when using multiple CASE … WHEN statements in the same SQL query?

梦想的初衷 提交于 2019-12-12 03:35:18

问题


After my previous question, I have an SQL query like the following:

SELECT * 
WHERE ... 
ORDER BY 
  CASE user_id WHEN 34 THEN 1 ELSE 2 END, 
  CASE status WHEN 'active' THEN 1 ELSE 2 END

As you can see in the above code, there are two CASE ... WHEN statements. What happens in this case? That is, how records will be ordered? May those "doubled" statements conflict?


UPDATE: I would like to make it to return records in this order: (1) records where user_id = 34 and status = 'active'; (2) records where status = 'active' (without user_id conditions); (3) all other records. How can I make that?


回答1:


First will come all records where user_id =34 with "active" status, then records with user_id=34 and status not "active", then records where user_id not equal 34 and status equals "active" , finally all remaining records where status is not "active"




回答2:


Order by are done in the order that you write them.

Your record will be ordered:

[first]
user_id = 34, status = 'active'
user_id = 34, status <> 'active'
user_id <> 34, status = 'active'
user_id <> 34, status <> 'active'
[last]



来源:https://stackoverflow.com/questions/13804756/what-does-it-happen-when-using-multiple-case-when-statements-in-the-same-sql

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