Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order items in MySQL by a fixed list?

Tags:

sql

mysql

I am going to have a fixed list of items to order by that I won't know until I run the query since there is a randomization step.

I would like to have something like the following:

Assume that is_launch_set will return 1, 3, 7, 11 but have been randomized to below:

SELECT * FROM items WHERE is_launch_set=1 ORDER BY id values (3,11,7,1);

Any ideas on how to achieve this? I was thinking maybe a find_in_set but not really sure.

like image 486
timpone Avatar asked Jun 07 '12 21:06

timpone


People also ask

How do you order things in MySQL?

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.

How do I use ORDER BY before group by?

When combining the Group By and Order By clauses, it is important to bear in mind that, in terms of placement within a SELECT statement: The GROUP BY clause is placed after the WHERE clause. The GROUP BY clause is placed before the ORDER BY clause.

How do I change the order of rows in MySQL?

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.


1 Answers

You can do that by using either:

ORDER BY FIND_IN_SET(id, '3,11,7,1')

or

ORDER BY FIELD(id, 3, 11, 7, 1)

or

ORDER BY CASE id WHEN 3 THEN 0
                WHEN 11 THEN 1
                 WHEN 7 THEN 2
                 WHEN 1 THEN 3
                        ELSE 4
         END
like image 189
zerkms Avatar answered Oct 19 '22 21:10

zerkms