What if you have to customize the sequence of order by clause on a column. Say, you have a integer column 'weight' that can have values ranging from 1 to 5 and you want to get the rows in the sequence 4,2,5,1,3. So what do you do? Here is a simple trick using the field function.
1: mysql> SELECT * FROM table ORDER BY FIELD(weight, 4, 2, 5, 1, 3);
Other approach can be to use CASE.. WHEN .. END statement as mentioned in the MySQL Documentation. The above code can be rewritten as:
1: mysql> SELECT *, CASE
2: -> WHEN weight = 1 THEN 4
3: -> WHEN weight = 2 THEN 2
4: -> WHEN weight = 3 THEN 5
5: -> WHEN weight = 4 THEN 1
6: -> WHEN weight = 5 THEN 3
7: -> END AS weight_custom
8: -> FROM table
9: -> ORDER BY weight_custom;
Such requirements are rare, just a food for thought.
Hope this blog was helpful to you. Keep posting your comments.
4 comments:
Thanks!
Been looking for hours for this!
You saved me a lot of time! Thank you!
Very nice.... thanks a lot
HI dear,
Thanks for this article.
it really helpful for me.
You saves my plenty of time with the help of this mysql order by method
thanks again
Post a Comment