2012-03-05 67 views
1

我使用下面的SQL查詢:Group By正在排序我不想要的結果集...?

SELECT `comment`.`id` AS `comment_id` , count(`comment_likes`.`comment_id`) AS `number_of_likes` 
FROM `comment` 
LEFT JOIN `comment_likes` ON `comment`.`id` = `comment_likes`.`comment_id` 
WHERE `comment`.`id` 
IN (10, 5, 7, 8, 3, 2, 9) 
GROUP BY `comment`.`id` 

這裏查詢的結果來爲:

comment_id number_of_likes 
2   0 
3   1 
5   0 
7   0 
8   0 
9   0 
10   0 

,我不想要......?我想要的條件相同的訂購,即在哪裏comment。 (10,5,7,8,3,2,9)

所以我希望得到的結果是這樣的:

comment_id number_of_likes 
10   0 
5   0 
7   0 
8   0 
3   1 
2   0 
9   0 

誰能幫我...?

在此先感謝.....

回答

2

添加明確ORDER BY。這可以是有益的功能是FIELD()

ORDER BY FIELD(comment.id, 10, 5, 7, 8, 3, 2, 9) 
+0

感謝ypercube,其工作非常需要... :) – PhpStudent 2012-03-05 09:32:54

2

你需要使用MySQL的FIELD(),以達到您想要的結果

SELECT `comment`.`id` AS `comment_id` , 
     count(`comment_likes`.`comment_id`) AS `number_of_likes` 
FROM `comment` LEFT JOIN `comment_likes` ON 
     `comment`.`id` = `comment_likes`.`comment_id` 
WHERE `comment`.`id` 
IN (10, 5, 7, 8, 3, 2, 9) 
GROUP BY `comment`.`id` 
ORDER BY FIELD(comment.id, 10, 5, 7, 8, 3, 2, 9)