首页 > 解决方案 > MySQL 在其中一行中复制 GROUP_CONCAT 内容

问题描述

我有 3 张桌子:

我需要一个返回包含这些列的行的查询:

这是我当前的查询,几乎可以正常工作:

SELECT store_cat.id_cat AS id,
CONCAT(store_cat.name, IFNULL(CONCAT(": ", GROUP_CONCAT(store_cat_attribute.name ORDER BY store_cat_attribute.position SEPARATOR ", "), ""), "")) AS name,
COUNT(DISTINCT store_item.id_item) AS products
FROM store_cat
LEFT JOIN store_item ON store_item.id_cat = store_cat.id_cat
LEFT JOIN store_cat_attribute ON store_cat_attribute.id_cat = store_cat.id_cat
WHERE store_cat.id_store = 1
GROUP BY store_cat.id_cat
ORDER BY name

问题是在其中一行中,奇怪的是,该name列复制了以下属性GROUP_CONCAT

类别:属性 1、属性 1、属性 2、属性 2、属性 3、属性 3

关于为什么会发生这种情况以及如何解决它的任何想法?谢谢!

在这里您可以查看 sqlfiddle:http ://sqlfiddle.com/#!9/7da2d3/5

标签: mysqljoingroup-by

解决方案


您在同一个查询中计算两个不同的东西( theGROUP_CONCAT和 the COUNT)。JOINto将store_item导致重复。您可以移动到选择列中的那个:

SELECT 
  store_cat.id_cat AS id, 
  CONCAT(store_cat.name, IFNULL(CONCAT(": ", 
    GROUP_CONCAT( 
       store_cat_attribute.name 
      ORDER BY store_cat_attribute.position 
      SEPARATOR ", "
    ), ""
    ), ""
   )) AS name, 
   (select count(distinct store_item.id_item) from store_item where store_item.id_cat = store_cat.id_cat) AS products 
FROM store_cat 
  LEFT JOIN store_cat_attribute ON store_cat_attribute.id_cat = store_cat.id_cat 
WHERE store_cat.id_store = 1 
GROUP BY store_cat.id_cat, store_cat.name
ORDER BY name

http://sqlfiddle.com/#!9/7da2d3/36


推荐阅读