Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom mysql sort by field value

Tags:

php

sorting

mysql

I have a question about mysql sorting. I have a database field with data like this 1,6,3,8,4. I exploded this field value and made custom query for another table: WHERE id='1' or id='6' or id='3'....

It works fine BUT the result is ASC by id. Is there a way to make the result appear at same order as the query?

like image 367
user1365447 Avatar asked May 11 '13 08:05

user1365447


People also ask

How do I create a custom sort in SQL?

By default SQL ORDER BY sort, the column in ascending order but when the descending order is needed ORDER BY DESC can be used. In case when we need a custom sort then we need to use a CASE statement where we have to mention the priorities to get the column sorted.

How do I sort values in MySQL?

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 sort a column by value in SQL?

To sort by a column: Type: SELECT columns FROM table ORDER BY sort_column [ASC | DESC]; columns is one or more comma-separated column names, sort_column is the name of the column on which to sort the result, and table is the name of the table that contains columns and sort_column.

How do I sort multiple columns in MySQL?

Summary. Use the ORDER BY clause to sort the result set by one or more columns. Use the ASC option to sort the result set in ascending order and the DESC option to sort the result set in descending order. The ORDER BY clause is evaluated after the FROM and SELECT clauses.


1 Answers

Use the FIELD() function in the ORDER BY clause:

ORDER BY FIElD(id, '1', '6', '3', ...);

See it in action here:

  • SQL Fiddle Demo
like image 63
Mahmoud Gamal Avatar answered Oct 13 '22 21:10

Mahmoud Gamal