简体   繁体   English

MySQL group_concat 和计数

[英]MySQL group_concat and count

I am trying to get the aspects of each category in a single query as follows:我试图在单个查询中获取每个类别的方面,如下所示:

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;

This query gives me the following result:这个查询给了我以下结果:

PHPMyAdmin 结果

As you can see, all the aspects of a category (Mobiles, in this case) are in a separate row.如您所见,一个类别(在本例中为 Mobile)的所有方面都在单独的一行中。 What i want is to get all aspects of all categories in a single row.我想要的是在一行中获得所有类别的所有方面。 So, i try this query:所以,我试试这个查询:

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;

This gives the below result:这给出了以下结果:

在此处输入图片说明

As you see, the count has increased for mobiles category.如您所见,手机类别的count有所增加。 There are only 271 items for Mobiles, but the second query almost multiplies this number by the no. Mobiles 只有 271 项,但第二个查询几乎将这个数字乘以 no。 of aspects for that category.该类别的方面。

I am not sure why is this happening.我不确定为什么会这样。 Any ideas would be welcome.欢迎任何想法。

Thanks in advance.提前致谢。

There may be repeated ids from table deals try using DISTINCT in your count functiondeals可能有重复的 id 尝试在您的计数函数中使用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 ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM