我有 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_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
关于MySQL 正在复制其中一行中的 GROUP_CONCAT 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55197633/