mysql - MySQL 在其中一行中复制 GROUP_CONCAT 内容
问题描述
我有 3 张桌子:
- 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
解决方案
您在同一个查询中计算两个不同的东西( theGROUP_CONCAT
和 the COUNT
)。JOIN
to将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
推荐阅读
- tensorflow - keras中的交叉熵损失计算错误
- php - 是否有一个 python 函数可以为 php.hash 获得相同的结果?
- python - Numpy:如何最好地对齐两个排序数组?
- sql - 识别缺失的行并在 SQL 中计算它们
- javascript - 从 Vue.js 中的子组件更新父组件
- c++ - 如何声明 std::chrono::duration
c++中的变量 - angular - 使用 @angular/fire/auth 登录会导致 localhost 出现 403 错误
- machine-learning - 如何在目标具有多标签的多分类问题中使用 lightGBM
- ios - 如何对特定于语言环境的本地通知进行单元测试
- c# - XAML - Blend 不支持 Base64 ImageSource