Order MySQL results according to how you want it
Posted on November 16th, 2008 in Database, MySql |
Here is a mysql function that is very useful when you want to order results according to how you want it, ofcourse when used with full query result its kinda useless, so i only suggest you to use this on a portion of a query. For example you have the following data:
Id | Name
1 | Tom
2 | Jerry
3 | Donald
4 | Roland
5 | Willie
And you want to order this so that Donald comes first followed by Willie, then randomized the remaining names.
In MySQL you could achieve this by using the function find_in_set. The answer to the query question above is:
SELECT id,IF(FIND_IN_SET(id, '3,5') > 0,FIND_IN_SET(id, '3,5'),3)
AS sort_column FROM table_names ORDER BY sort_column,RAND()
find_in_query would find 3 and 5 (3,5) in the field id and return a chronological order from 1 to n, the reason why we use IF is that for the remainding name the function would return 0 coz it didnt found the other id in the find_in_query arguments, so to have an ascending order and have Donald and Willie goes first, we must assign 3 (thats 3,5 which is 2 numbers plus 1) to the sort_column.
Hope you guys understand this.












