-->

What does it happen when using multiple CASE … WHE

2019-09-17 17:29发布

问题:

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]