views:

21

answers:

2

I have an array of IDs that are already sorted in descending order as to their relevancy, but I need to make a query to get the details of each ID.

How can I get the results to return so that they are in the order of my Where statement?

SELECT DISTINCT `content_object_set_instances`.`id` AS content_object_set_instance_id, `content_object_set_instances`.`title` AS content_object_set_instance_title, `content_object_set_instances`.`name` AS content_object_set_instance_name, `content_object_set_instances`.`description` AS content_object_set_instance_description FROM (`content_object_set_instances`) WHERE `content_object_set_instances`.`id` = 213 OR `content_object_set_instances`.`id` = 216 OR `content_object_set_instances`.`id` = 212

Currently they are returning as such:

ID  | title |  name  |  description
212  | Mr Spot  | name...  | description...
213  | Bamboo  | name...  | description...
216  | Beautious  | name...  | description...
+1  A: 

If you will always know the ids that you are going to return, you can make you ORDER BY clause equal to the reverse order that you want to return, so:

ORDER BY `content_object_set_instances`.`id`= 212,
`content_object_set_instances`.`id`= 216,
`content_object_set_instances`.`id`= 213
PIM
Thank you! I went with Jason's version as it was a bit cleaner.
sterling
+3  A: 

In your particular case, with only 3 values, you can use the ORDER BY FIELD(). Try the following:

SELECT DISTINCT ... FROM `content_object_set_instances`
WHERE ...
ORDER BY FIELD(id, 213, 216, 212)
Jason McCreary
Thank you, that worked brilliantly.
sterling
You're welcome.
Jason McCreary