I have the following table
DROP TABLE IF EXISTS `test`.`foo`; CREATE TABLE `test`.`foo` ( `id` int(10) unsigned NOT NULL auto_increment, `name` varchar(45) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Then I try to get records based on the primary key
SELECT * FROM foo f where f.id IN (2, 3, 1);
I then get the following result
+----+--------+ | id | name | +----+--------+ | 1 | first | | 2 | second | | 3 | third | +----+--------+ 3 rows in set (0.00 sec)
As one can see, the result is ordered by id. What I'm trying to achieve is to get the results ordered in the sequence I'm providing in the query. Given this example it should return
+----+--------+ | id | name | +----+--------+ | 2 | second | | 3 | third | | 1 | first | +----+--------+ 3 rows in set (0.00 sec)
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.
MySQL UPDATE UPDATE with ORDER BY and LIMITIf the ORDER BY clause is specified in your update SQL statement, the rows are updated in the order that is specified. If LIMIT clause is specified in your SQL statement, that places a limit on the number of rows that can be updated.
The order doesn't matter, actually, so you are free to order them however you'd like.
As the other answer mentions: the query you posted has nothing about what order you'd like your results, just which results you'd like to get.
To order your results, I would use ORDER BY FIELD()
:
SELECT * FROM foo f where f.id IN (2, 3, 1) ORDER BY FIELD(f.id, 2, 3, 1);
The argument list to FIELD
can be variable length.
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