Multi-value sort database records in a specific order
]Suppose you have a table with an index key and a non-index field x_field
. You need to find all records with specific values and return them and sort the results according to multiple values in a specific order.
For example, if you have the following table:
x_field | |
---|---|
123 | a |
124 | a |
] | 124 |
125 | |
126 | |
f | |
b | b |
129 | a |
130 | |
131 | |
132 | |
133 |
134
135 | |
---|---|
] | ] | ]
: | |
x_field | |
127 | f |
133 | p |
134 | p |
135 | i |
123 | a |
124
SELECT *
FROM table
WHERE id NOT IN (126)
ORDER BY x_field 'f', 'p', 'i', 'a'
a125a
...
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
a
You initially tried using the following query:
However, this query returns no results.
The solution to this problem is to use the CASE
x_field value in the desired order: ]
...
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 -- For fallback values not in the IN clause (for example: x_field = 'b')
END, id
x_field
value equal to 'f', value 2 to the value equal to 'p', value 3 to the value equal to 'i', and value 4 to the value equal to 'a'. For values not in thefield. | This method ensures that the results are sorted in the desired order, even if the | x_field
---|
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3