I am looking for a special kind of requirement from my query on MySQL database where I want to apply order by in a different manner. E.g. In a DB with the fields user_id and user_rating and user_department with following data.
+------------------------------------------------------+
| user_id | user_rating | user_department |
+------------------------------------------------------+
| 1 | 102 | A |
| 2 | 33 | B |
| 3 | 43 | C |
| 4 | 54 | A |
| 5 | 63 | A |
| 6 | 214 | B |
| 7 | 82 | A |
| 8 | 87 | C |
| 9 | 43 | A |
| 10 | 98 | A |
| 11 | 73 | C |
| 12 | 31 | A |
+------------------------------------------------------+
Given above structure I want to sort results in the order of their user_rating for each_department and I need at max 5 records from each user_department among which intial 3 records should be in order of their rating but rest 2 should be random.
So In above case Output will be something similar to:
+------------------------------------------------------+
| user_id | user_rating | user_department |
+------------------------------------------------------+
| 1 | 102 | A |
| 10 | 98 | A |
| 7 | 82 | A |
| 12 | 31 | A |
| 5 | 63 | A |
| 6 | 214 | B |
| 2 | 33 | B |
| 8 | 87 | C |
| 11 | 73 | C |
| 3 | 43 | C |
+------------------------------------------------------+
I tried options available over web for custom order by, like using FIELD function But couldn't find that much useful here. Also tried to solve it using subquery but that option also does Not look feasible as MySql does Not allow me to use IN and LIMIT keywords together in my query.
Is there any better/simpler way to solve this.