MySQL group_concat 和计数
Posted
技术标签:
【中文标题】MySQL group_concat 和计数【英文标题】:MySQL group_concat and count 【发布时间】:2014-05-25 07:02:58 【问题描述】:我正在尝试在单个查询中获取每个类别的各个方面,如下所示:
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;
这给出了以下结果:
如您所见,手机类别的count
有所增加。 Mobiles 只有 271 项,但第二次查询几乎将这个数字乘以编号。该类别的方面。
我不确定为什么会这样。欢迎任何想法。
提前致谢。
【问题讨论】:
我猜你重复了表 c 中的 id 尝试count(DISTINCT c.id )
哦!这么滑!非常感谢@m-khalid-junaid!您能否将其发布为答案,以便我接受。
【参考方案1】:
deals
表中可能有重复的 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 ...
【讨论】:
感谢您的快速解决!正在查看错误的列以查找问题。以上是关于MySQL group_concat 和计数的主要内容,如果未能解决你的问题,请参考以下文章
Mysql group_concat 的重复键和 1 个查询中多列的重复计数(查询优化)