简体   繁体   English

MySQL在一行之一中复制GROUP_CONCAT内容

[英]MySQL is duplicating GROUP_CONCAT content in one of the rows

I have 3 tables: 我有3张桌子:

  • store_cat: categories store_cat:类别
  • store_cat_attribute: attributes for each category store_cat_attribute:每个类别的属性
  • store_item: items which are optionally linked to a category store_item:可以链接到类别的项目

I need a query that returns rows that contain these columns: 我需要一个返回包含以下列的行的查询:

  • Category: Attribute1, Attribute2, Attribute3 类别:Attribute1,Attribute2,Attribute3
  • Item COUNT 项目数

This is my current query, which works almost fine: 这是我当前的查询,几乎可以正常工作:

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

The problem is that in one of the rows, oddly enough, the name column is duplicating the attributes in the GROUP_CONCAT : 问题是奇怪的是,在其中一行中, name列正在复制GROUP_CONCAT的属性:

Category : Attribute1, Attribute1, Attribute2, Attribute2, Attribute3, Attribute3 类别 :属性1,属性1,属性2,属性2,属性3,属性3

Any ideas on why this is happening and how to solve it? 关于为什么发生这种情况以及如何解决的任何想法? Thanks! 谢谢!

Here you can check the sqlfiddle: http://sqlfiddle.com/#!9/7da2d3/5 在这里您可以检查sqlfiddle: http ://sqlfiddle.com/#!9/7da2d3/5

You are calculating two different things in same query (the GROUP_CONCAT and the COUNT ). 您正在同一查询中计算两个不同的事物( GROUP_CONCATCOUNT )。 The JOIN to store_item will cause the duplicates. JOINstore_item将导致重复。 You can move to the one into the select column: 您可以将其移到选择列中:

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 http://sqlfiddle.com/#!9/7da2d3/36

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

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