简体   繁体   中英

How is MySQL interpreting: ORDER BY CASE status WHEN 1 THEN 1 ELSE -1 END DESC

I am working on an existing project and found this SQL statement. After reviewing the MySQL documentation , I'm a still confused by the syntax and how MySQL is interpreting it.

I have a column called status that can be 0 (inactive), 1 (active), 2 (completed), 3 (testing).

ORDER BY CASE status WHEN 1 THEN 1 ELSE -1 END DESC, id ASC

What confuses me is THEN 1 ELSE -1 . In the documentation it mentions that you place a statement_list after THEN . I would expect to see something like this:

ORDER BY CASE status WHEN 1 THEN status ELSE -1 (or some other value that will be ignored) END DESC, id ASC

How is mysql interpreting THEN 1 ELSE -1 ? I guess I'm curious how this statement is returning the right results. It is basically doing this: If status = 1 then ORDER BY status DESC else ignore the order by statement.

ORDER BY CASE status WHEN 1 THEN 1 ELSE -1 END DESC, id ASC

This means it'll order by (1 or -1 DESC, id ASC) effectively.

Based on the value of status it'll put a 1 or -1 as the first expression to order by and "id ASC" is the tie breaker. Rows with status = 1 will come first in the result (ordered by id in ascending order) and rows with other values for status will be returned after that (their order is not specified any further).

It would order by active status first (1) because of the DESC clause, then everything else would be returned after that. Anything assigned -1 may be randomly ordered.

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