2014-04-11 178 views
3

我試圖讓每個類別的方面,用於在單一的查詢,如下所示:MySQL的GROUP_CONCAT和計數

SELECT b.`id` AS parent_id, b.`name` AS parent_name, 
    a.`id` AS child_id, a.`name` AS child_name, a.`pageid` AS t_id, 
    COUNT(c.`id`) AS deals_in_cat, 
    d.`aspect_values` AS aspects 
     FROM `category_parent` AS a 
     LEFT JOIN `navigation_filters_weightage` AS d ON a.`id` = d.`cat_id`, 
     `deals_parent_cat` AS b, 
     `deals` AS c 
    WHERE a.`parent_id` = b.`id` 
    AND c.`ebaydeals_category` = a.`id` 
     GROUP BY a.`id`, d.`frequency` 
     ORDER BY b.`order` ASC, a.`order` ASC, d.`frequency` DESC; 

該查詢給我下面的結果:

PHPMyAdmin Result

正如你可以看到,類別的所有方面(在這種情況下爲手機)都在單獨的行中。我想要的是將所有類別的所有方面都放在一行中。所以,我嘗試此查詢:

SELECT b.`id` AS parent_id, b.`name` AS parent_name, 
    a.`id` AS child_id, a.`name` AS child_name, a.`pageid` AS t_id, 
    COUNT(c.`id`) AS deals_in_cat, 
    GROUP_CONCAT(DISTINCT d.`aspect_values` ORDER BY d.`frequency` DESC) AS aspects 
     FROM `category_parent` AS a 
     LEFT JOIN `navigation_filters_weightage` AS d ON a.`id` = d.`cat_id`, 
     `deals_parent_cat` AS b, 
     `deals` AS c 
    WHERE a.`parent_id` = b.`id` 
    AND c.`ebaydeals_category` = a.`id` 
     GROUP BY a.`id` 
     ORDER BY b.`order` ASC , a.`order` ASC; 

這給瞭如下的結果:

enter image description here

正如你看到的,count增加了對手機類別。移動設備只有271項,但第二個查詢幾乎將該數字乘以不。該類別的方面。

我不知道爲什麼會發生這種情況。任何想法都會受到歡迎。

在此先感謝。

+1

我想你已經從重複表IDÇ嘗試'計數(DISTINCT c.id)' –

+0

哦!這樣的滑倒!非常感謝@ m-khalid-junaid!你可以張貼這個答案,以便我可以接受它。 –

+0

已將此貼發送給答案 –

回答

3

有可能從表deals重複IDS嘗試在計數功能使用DISTINCT

SELECT b.id AS parent_id, 
    b.name AS parent_name, 
    a.id AS child_id, 
    a.name AS child_name, 
    a.pageid AS t_id, 
    count(DISTINCT c.id) AS deals_in_cat ... 
+1

謝謝快速解決!正在看問題的錯誤列。 –

+1

很好的解決方案,我用我的解決方案HAVING COUNT – FosAvance