[英]MySQL is duplicating GROUP_CONCAT content in one of the rows
我有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
您正在同一查詢中計算兩個不同的事物( GROUP_CONCAT
和COUNT
)。 JOIN
到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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.