Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql - order by field not working properly

Tags:

php

mysql

suppose I've a database , the table contains rows with ides from 1 to 20 .

i want to return 3 rows with id 3,4,1 first and then return the other rows . this is my code :

    SELECT id
FROM prod
ORDER BY field( id, 3, 4, 1 ) 
LIMIT 20

this is the result of this code :

id
13 
17 
16 
15 
 7 
 6 
 5 
 2 
 3 
 4 
 1

strangely the 3 rows that I need to come first are showing at the end ,

How can I bring these 3 rows to the top of the list ?

Thanks

like image 329
mohamad bagheri Avatar asked May 11 '15 11:05

mohamad bagheri


People also ask

How to ORDER BY FIELD in MySQL?

To sort the rows in the result set, you add the ORDER BY clause to the SELECT statement. In this syntax, you specify the one or more columns that you want to sort after the ORDER BY clause. The ASC stands for ascending and the DESC stands for descending.

How do I arrange in ascending order 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 you use like in order?

When you use LIKE operator to search and fetch the matched results from the database, the records are selected based on their entry. On another hand, the ORDER BY keyword allows you to sort the result-set in ascending or descending order based on a specific column.

What is field function in SQL?

The FIELD() function returns the index position of a value in a list of values. This function performs a case-insensitive search. Note: If the specified value is not found in the list of values, this function will return 0. If value is NULL, this function will return 0.


2 Answers

The other way is to use case-when and giving each id an order value

select * from prod 
order by 
case 
  when id = 3 then 0  
  when id=4 then 1 
  when id=1 then 2 
  else 3 
end,id 
limit 20
;
like image 183
Abhik Chakraborty Avatar answered Sep 29 '22 03:09

Abhik Chakraborty


You can use DESC:

SELECT id
FROM prod
ORDER BY field( id, 3, 4, 1 ) DESC
LIMIT 20

The issue is that MySQL puts NULL values first when you do an ascending order by.

If you actually want the rows in the order 3, 4, 1, then reverse them in the field statement:

SELECT id
FROM prod
ORDER BY field( id, 1, 4, 3 ) DESC
LIMIT 20

Or, if you wanted to be fancy:

ORDER BY - field( id, 3, 4, 1 ) DESC
like image 35
Gordon Linoff Avatar answered Sep 29 '22 03:09

Gordon Linoff