Select in Mysql sorted by the WHERE condition

Asked

Viewed 30 times

1

I have a database in Mysql designed like this:

id, nome

At the following values:

1, Banana
2, Maçã
3, Uva
4, Laranja

I have a select like this:

select * FROM table WHERE id = 2 OR id = 1 OR id = 4;

The answer I get is ordered by the ID, because I didn’t put any ORDER BY:

1, Banana
2, Maçã
4, Laranja

But I need the order to be by the condition written in the WHERE:

2, Maçã
1, Banana
4, Laranja

How to do it? Remembering that the example is simplified, focusing only on my doubt.

  • 1

    If you know exactly which Ids to search for you can just pick based on the ID as an input in the application (in PHP for example) instead of order in the query.

  • 1

    Disregarding search for performance or best practices in the query, UNION could not help? Something like: (SELECT * FROM fruit WHERE id = 2) UNION (SELECT * FROM fruit WHERE id = 1) UNION (SELECT * FROM fruit WHERE id = 4).

1 answer

4


Hello, you can use so, where it is very practical including adding values dynamically:

SELECT id, nome FROM table WHERE id IN (2,1,4) ORDER BY FIELD(id, 2,1,4)

I hope I’ve helped

Browser other questions tagged

You are not signed in. Login or sign up in order to post.