Handy MySQL - ORDER BY FIELD
Had a slight problem today and found a neat solution.
My problem was I wanted to sort properties by status and date added but needed the status to show in a priority fashion.
For example, I wanted the order of the property status to be For Sale, For Rent, Sale Agreed and also to sort by date added.
I couldnt use ORDER BY propertyStatus, propertyDateAdded because then For Rent would come before For Sale.
The solution was to use ORDER BY FIELD
Syntax: ORDER BY FIELD(propertyStatus,'For Sale','For Rent','Sale Agreed'), propertyAdded DESC
This assumes you need some order though. Another good application of this would be ordering a field where its 'HIGH','MEDIUM','LOW'
Comments
BTW - when I tried to leave comment using Opera I got message "Sorry. There was an error."
It's due to a space left between FIELD and (. FIELD( will fix it.
order by field(FIELD,'First Result') DESC,FIELD
seems to be working as expected. :)
ps, Ireland's a great country. i look forward to visiting again.
select username from users order by case when username='taba.ru' then 3 when username='scripted.in' then 2 when username='udobnee.net' then 1 else -1 end DESC, username ASC;
to get some records at the top of selection
Now I see function FIELD do the same but more clear to understand