For example: select * from T where T.id IN(4,78,12,45)
I want the returned record set just order by the position in the 'IN' clause. How can I do this?
The MySQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
Answer: ORDER BY is a clause that is typically used along with SELECT queries in MySQL and is used to return the result set sorted in the given order against the given column or field in the table.
An "ALTER TABLE ORDER BY" statement exist in the syntaxes accepted by MySQL. According to the documentation, this syntax: - only accept *one* column, as in "ALTER TABLE t ORDER BY col;" - is used to reorder physically the rows in a table, for optimizations.
The ORDER BY clause is used to sort the result-set in ascending or descending order.
You could do it using FIND_IN_SET, e.g.
SELECT * FROM T WHERE T.id IN(4,78,12,45)
ORDER BY FIND_IN_SET(T.id,'4,78,12,45');
While you do have to duplicate the list, if you're generating the query in code this isn't a huge problem.
In the general case, you can't. SQL doesn't guarantee order unless you use the ORDER BY
clause, and it can't be tied into the contents of an IN
statement.
However, if you can build a temporary table that orders the values you're selecting from, you can join on that table and order by it.
For example, you have a temporary table that contains something like the following:
id | order
----+------
4 | 1
78 | 2
12 | 3
45 | 4
Then you can order it like this:
SELECT T.*
FROM T
INNER JOIN temp
ON T.id = temp.id
ORDER BY temp.order ASC
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