mysql - 为什么 group_concat 会为每一行带来所有产品 ID

标签 mysql database group-concat

这是我的查询,它有一些连接,除了 GROUP_CONCAT(p.product_id) 和 SUM(p.price) 部分外,其他都运行良好。

SELECT ts.name as main_name, tp.class_id, ts.step_number, GROUP_CONCAT(p.product_id) as product_id, SUM(p.price) as price
from template as t 
JOIN template_step as ts on ts.template_id=t.template_id 
JOIN template_product as tp on tp.template_id=ts.template_id 
JOIN product as p on p.product_id=tp.product_id 
JOIN product_description as pd on pd.product_id=p.product_id 
where t.template_id = '59' 
group by tp.class_id, ts.step_number 
ORDER by ts.step_number, tp.class_id

问题是返回的 product_ids 和 sum 字段的元素是重复的

这是我查询的数据

Networking  1   1    88,156,151,275,48,101,274,133,154,125,135,148,63,63    3070.0000
Networking  2   1    275,235,164,274,154,124,169,148,62,98,62,277,191,270   3695.0000
Networking  3   1    92,98,216,181,133,187,272,154,274,148,126,62,62,165    4970.0000
Back Office 1   2    63,88,156,151,275,48,101,274,133,154,125,135,148,63    3070.0000
Back Office 2   2    275,235,164,274,154,124,169,148,62,98,62,277,191,270   3695.0000
Back Office 3   2    62,165,92,98,216,181,133,187,272,154,274,148,126,62    4970.0000
Data Back   1   3    148,63,63,88,156,151,275,48,101,274,133,154,125,135    3070.0000
Data Back   2   3    270,275,235,164,274,154,124,169,148,62,98,62,277,191   3695.0000
Data Back   3   3    62,62,165,92,98,216,181,133,187,272,154,274,148,126    4970.0000
Kitchen     1   4    135,148,63,63,88,156,151,275,48,101,274,133,154,125    3070.0000

每个类应该只返回 1 或 2 个 product_id。如果有任何其他信息我可以提供帮助别人帮助我我可以提供任何东西..db 结构..ext..

最佳答案

GROUP_CONCAT()除非您使用 DISTINCT,否则不会删除重复的行:

GROUP_CONCAT([DISTINCT] expr [,expr ...]
             [ORDER BY {unsigned_integer | col_name | expr}
                 [ASC | DESC] [,col_name ...]]
             [SEPARATOR str_val])

关于mysql - 为什么 group_concat 会为每一行带来所有产品 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6497526/

相关文章:

mysql - 为什么 MySQL 服务器不将表写入文件?

Php MySql 未知错误

mysql - 如何使用MySQL优化表是否包含10000个条目的查询?

mysql - 将新列插入表的存储过程

MySQL 全文搜索?

mysql - 查询中 Mysql SUM 和 GROUP_CONCAT 的问题

mysql - 如何按(多个值)中的位置对 GROUP_CONCAT 列进行排序?

php - 插入新更新时将以前的状态更新为“死亡”

mysql - 如何在mysql中选择具有NULL值的列表 'IN'的所有行?

MySQL IF IN GROUP_CONCAT 中断