2010-07-24 47 views
1

我有一個已經按照降序排列的ID的數組,因爲它們的相關性,但我需要進行查詢以獲取每個ID的詳細信息。我如何以與OR語句相同的順序排列mysql結果?

我怎樣才能得到結果返回,以便他們在我的Where語句的順序?

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 

目前,他們正在返回這樣:

ID | title | name | description 
212 | Mr Spot | name... | description... 
213 | Bamboo | name... | description... 
216 | Beautious | name... | description... 

回答

3

你的具體情況,只用3個值,你可以使用ORDER BY FIELD()。請嘗試以下操作:

SELECT DISTINCT ... FROM `content_object_set_instances` 
WHERE ... 
ORDER BY FIELD(id, 213, 216, 212) 
+0

謝謝,那非常出色。 – sterling 2010-07-24 03:40:22

+0

不客氣。 – 2010-07-24 03:41:58

+0

如果有N個值呢? – Haz 2012-05-31 13:15:23

1

如果你將永遠知道你要返回的ID,就可以讓你ORDER BY子句等於相反的順序要返回,所以:

ORDER BY `content_object_set_instances`.`id`= 212, 
`content_object_set_instances`.`id`= 216, 
`content_object_set_instances`.`id`= 213 
+0

謝謝!我和Jason的版本一樣,因爲它有點乾淨。 – sterling 2010-07-24 03:41:07

相關問題