Display Mysql search results according to the sequence shown in the in clause

Asked

Viewed 71 times

0

How do I sort the results of a query as a sequence displayed in the In clause? That is, the order of the lines must respect the same order of values indicated in this clause.

Example:

sql = select var_valor from tabela where var_codigo in (4,2,7);

In this case, the result should first display the var_value of code 4, after code 2 and last code 7.

Below is the code in SQL Fiddle to illustrate my question: http://sqlfiddle.com/#! 9/4c663e/10

1 answer

2


Use the ORDER BY FIELD(), thus:

sql = select var_valor from tabela where var_codigo in (4,2,7)
order by FIELD(var_codigo, 4,2,7);

In the case of the example you posted in SQL Fiddle, it would look like this:

select con_valor as valor from tabela where con_variavel in ('corpo','rodape','exibesoma')
order by FIELD(con_variavel, 'corpo','rodape','exibesoma');

Read this documentation to learn more about the function FIELD()

  • Thank you Murilo!!!

Browser other questions tagged

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