Request without autosave

Possible duplicates:
Order MySQL results by IN sequence?
Ordering in order of value in an SQL IN () clause

I have the following table called "Products"

id desc
1  BL10
2  BL15
3  BL45
4  BL50

Well, this is my request. SELECT * FROM Products WHERE id IN(3,1,4,2) I want it to appear in the same order as the IN clause, i.e. 3,1,4,2:

id desc
3  BL45
1  BL10
4  BL50
2  BL15

but when I execute it, it shows the ordered, How can I get it? I am using MSSQL 2005

+3
source share
3 answers

Your proposal INwill not sort your result set, but instead, your results will be returned in the order in which they appear in the request.

, ORDER BY , :

SELECT * 
FROM Products
WHERE id IN (3,1,4,2)
ORDER BY (CASE WHEN id = 3 THEN 0
               WHEN id = 1 THEN 1
               WHEN id = 4 THEN 2
               WHEN id = 2 THEN 3 END)

( DBMS-, , , , )

+4
SELECT * FROM Products WHERE id IN (3, 1, 4, 2)
ORDER BY FIELD (id, 3, 1, 4, 2)
+1

, , , , SortOrder, ORDER BY:

SELECT * FROM WHERE id IN (3,1,4,2) ORDER BY SortOrder

SortOrder :

Id  SortOrder
1   20 
2   40
3   10
4   30
0

Source: https://habr.com/ru/post/1761590/


All Articles