MySQL 正在复制其中一行中的 GROUP_CONCAT 内容

标签 mysql join group-by

我有 3 张 table :

  • store_cat:类别
  • store_cat_attribute:每个类别的属性
  • store_item:可以选择链接到类别的商品

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

  • 类别:属性 1、属性 2、属性 3
  • 商品 COUNT

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

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

最佳答案

您正在同一查询中计算两个不同的事物(GROUP_CONCATCOUNT)。 JOINstore_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

关于MySQL 正在复制其中一行中的 GROUP_CONCAT 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55197633/

相关文章:

Mysql cluster 7.2.2忽略设置和TABLE IS FULL错误

c# - MySQL 到 MS SQL Server...需要有关最佳方法的建议

mysql 使用 join 查询重复数据

Mysql从数据库中获取数据第一表和第二表3列中的一列

mysql - 获取最低Time对应的DateTime

php - mySQL 排序和不同

sql - MySQL - 查找引用指定索引的条目

mysql - SQLSTATE[HY000] : General error: 1364 Field 'name' doesn't have a default value

mysql - 连接两个表并使组和总和正确

mysql - 分组时的问题