数据库
首页 > 数据库> > MySQL group_concat和计数

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;

该查询给我以下结果:

如您所见,类别的所有方面(在本例中为手机)都在单独的行中.我想要的是将所有类别的所有方面都放在一行中.因此,我尝试此查询:

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;

得到以下结果:

如您所见,手机类别的数量有所增加.手机只有271个项目,但是第二个查询几乎将此数字乘以编号.该类别的方面.

我不确定为什么会这样.任何想法都将受到欢迎.

提前致谢.

解决方法:

表交易中可能有重复的ID,请尝试在您的count函数中使用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 ...

标签:count,group-concat,left-join,sql,mysql
来源: https://codeday.me/bug/20191121/2055044.html