To avoid another heaving PHP/other language sorting process on results from complex SQL queries I wanted to reorder my way, I’ve discovered an interesting property in SQL to order according special values using SQL FIELD (documentation on MySQL FIELD here, and scroll).
Example :
-- Let's I have a table of articles (id, name, color, size) -- and I want the red articles first, then green, then yellow -- and finally blue SELECT * FROM articles ORDER BY FIELD(color, 'red','green','yellow', 'blue');
Then, to be sure that you won’t have any extra results that won’t match your color criteria and therefore be in the first place of your sorted list, you can add a IN on the field you want to sort.
Example :
SELECT * FROM articles WHERE color IN ('red','green','yellow', 'blue') ORDER BY FIELD(color, 'red','green','yellow', 'blue');
Nice huh ?
Latest posts by Fab (see all)
- La Horde du Contrevent : review - 13 October 2024
- For Whom the Bells Tolls: review - 4 August 2024
- Self Aware On Air Neon Sign - 8 June 2024
just what i was looiking for. it helped me a lot. thanks a lot :)