Hello guys,
Most of time we face the problem order by within IN() values . Mysql provides the function FIELD(), It will sort fetched IN() data according to requirment . The FIELD function returns the position of the first string in the remaining list of strings
For Example:-
| id | name |
^--------^---------^
| 5 | B |
| 6 | B |
| 1 | D |
| 15 | E |
| 17 | E |
| 9 | C |
| 18 | C |
If you fetch data without FIELD function , It may give result unordered according to within IN() values. If we use FIELD function as given below , It will gives sorted result.
SELECT id, name
FROM mytable
WHERE name IN ('B', 'A', 'D', 'E', 'C')
ORDER BY FIELD(name, 'B', 'A', 'D', 'E', 'C')
0 Comment(s)