I am using the following SQL to select records from MySQL database:
SELECT * FROM cms_product WHERE id IN (3,22,1);
The results order equals "ORDER BY id ASC", so as in example records 1,3,22 are returned. How can I get them ordered in the exact way as typed in IN clause? So ordered as 3,22,1 ? Thank you.
To select rows using selection symbols for character or graphic data, use the LIKE keyword in a WHERE clause, and the underscore and percent sign as selection symbols. You can create multiple row conditions, and use the AND, OR, or IN keywords to connect the conditions.
ROW_NUMBER (Window Function) ROW_NUMBER (Window Function) is a standard way of selecting the nth row of a table. It is supported by all the major databases like MySQL, SQL Server, Oracle, PostgreSQL, SQLite, etc.
For SQL Server, a generic way to go by row number is as such: SET ROWCOUNT @row --@row = the row number you wish to work on.
Numerous options -
Preferred, being ANSI-92 it's portable to other databases.
SELECT *
FROM cms_product
WHERE id IN (3,22,1)
ORDER BY CASE id
WHEN 3 THEN 1
WHEN 22 THEN 2
WHEN 1 THEN 3
END
SELECT *
FROM cms_product
WHERE id IN (3,22,1)
ORDER BY FIND_IN_SET(id, '3,22,1');
SELECT *
FROM cms_product
WHERE id IN (3,22,1)
ORDER BY FIELD(id, 3, 22, 1);
Reference:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With