【发布时间】:2012-11-22 12:25:42
【问题描述】:
我在使用 group_concat 连接表时遇到问题。以下是详细信息。
table_orders:
item_cd order_id descs quantity status seq_no
1 100 coca-cola 2 A 232
2 100 pizza 1 A 233
3 101 cheeseburger 5 A 234
4 102 pepsi 4 A 235
4
table_instructions:
item_cd instruction
3 more cheese
3 less vegetable
cancelled_item_table:
quantity seq_no
1 234
1 234
1 235
现在我想要实现的是这样的:
item_cd descs quantity instructions cancelled_item
1 coca-cola 2 - -
2 pizza 1 - -
3 cheeseburger 2 more cheese, less vegetable 1,1
4 pepsi 4 - 1
这是我当前的查询:
SELECT
ord.item_cd,
ord.order_id,
ord.descs,
ord.quantity,
GROUP_CONCAT(x.quantity) as cancelled,
GROUP_CONCAT(i.instruction) as instruct
FROM table_orders ord
LEFT JOIN cancelled_item_table x ON ord.seq_no = x.seq_no
LEFT JOIN table_instructions i ON ord.item_cd = i.item_cd
WHERE ord.status = 'A'
GROUP BY ord.order_id
这是输出:
item_cd descs quantity instructions cancelled_item
1 coca-cola 2 - 1
2 pizza 1 - 1
3 cheeseburger 2 more cheese, more cheese,
less vegetable, less vegetable 1,1,1,1
4 pepsi 4 - 1
如果你注意到,芝士汉堡有 2 个取消的项目和 2 条指令,但输出是 4,看起来像是在相乘。
【问题讨论】:
-
你能把结构放在sqlfiddle.com吗?
-
我认为您可能打错了一些东西,因为我没有通过相同的输入/查询得到相同的输出(特别是有两个 ord_id = 100);
-
这可能是由于 MySQL 宽松的
GROUP BY规则作用于比您在输出中实际看到的更多的行组。您只有GROUP BY order_id,但您的SELECT中有其他列。按照@ExplosionPills 的建议修复数据,然后我们可以帮助解决查询。 -
例如看这个sqlfiddle.com/#!2/31b58/4。将
instruction添加到GROUP BY时,很明显您正在处理 2 行 -
我已经编辑了我的问题,请特别查看说明字段。
标签: mysql group-by group-concat