Home > Database > Mysql Tutorial > How Can a CASE Expression Order SQL Results by Specific Values?

How Can a CASE Expression Order SQL Results by Specific Values?

DDD
Release: 2025-01-08 17:57:41
Original
733 people have browsed it

How Can a CASE Expression Order SQL Results by Specific Values?

Use CASE expressions to sort SQL results by specific values

When retrieving data from a table, you often need to sort the results based on multiple values ​​in a specific order. In this case, the task is to extract records from a table based on specified keys and non-indexed fields and sort the results by multiple values ​​in a specific sequence.

To meet this requirement, a CASE expression can be used to achieve the desired ordering instead of using the traditional ORDER BY syntax. The syntax of CASE expression is as follows:

<code class="language-sql">CASE
   WHEN condition1 THEN value1
   WHEN condition2 THEN value2
   ...
   ELSE valueN
END</code>
Copy after login

In this example, the CASE expression is used to assign a specific order to each value in x_field. For example, the values ​​'f', 'p', 'i' and 'a' are assigned sequence numbers 1, 2, 3 and 4 respectively. Any other values ​​that do not match these specific values ​​will be assigned the default sequence number 5.

Here is an example of how a CASE expression can be added to a SQL query:

<code class="language-sql">SELECT *
FROM table
WHERE
   x_field IN ('f', 'p', 'i', 'a')
ORDER BY
   CASE x_field
      WHEN 'f' THEN 1
      WHEN 'p' THEN 2
      WHEN 'i' THEN 3
      WHEN 'a' THEN 4
      ELSE 5 -- 对不在IN子句中的值(例如:x_field = 'b')的回退值
   END, id</code>
Copy after login

By using a CASE expression, the results will be sorted according to the assigned sequence number, effectively sorting the values ​​'f', 'p', 'i' and 'a' in the specified sequence.

The above is the detailed content of How Can a CASE Expression Order SQL Results by Specific Values?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template