S
S
Sergey Kiryanov2020-05-14 14:14:16
MySQL
Sergey Kiryanov, 2020-05-14 14:14:16

How to solve the problem with such sorting?

There is a request like

SELECT * FROM `table` ORDER by `price` DESC

Is it possible to somehow execute such a query, but manually specify in the queries the specific IDs that should be selected first, regardless of their `price` ?

id price
1 100
2 300
3 50
4 600
5 10
6 1000

That is, I should get:
3 50
5 10
6 1000
4 600
2 300
1 100

Specifying ID 3.5 manually that they should be the first

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
d-stream, 2020-05-14
@d-stream

A universal solution is to sort by a calculated expression.
Well, or for frequent use of a large list - by the sort_order field of the attached table

L
Lazy @BojackHorseman MySQL, 2020-05-14
Tag

...
ORDER BY `id` IN (<ids_coma_separated>) DESC

K
Konstantin Tsvetkov, 2020-05-14
@tsklab

ORDER BY CASE ID WHEN 3 THEN 1 WHEN 5 THEN 2 ELSE 3 END, Price DESC

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question