簡體   English   中英

MySQL在一行之一中復制GROUP_CONCAT內容

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

我有3張桌子:

  • store_cat:類別
  • store_cat_attribute:每個類別的屬性
  • store_item:可以鏈接到類別的項目

我需要一個返回包含以下列的行的查詢:

  • 類別:Attribute1,Attribute2,Attribute3
  • 項目數

這是我當前的查詢,幾乎可以正常工作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM