我有一个按预期工作的查询:
查询
SELECT name, date, enddate, abo_name, bill_id
FROM (
SELECT CONCAT(c.firstname, " ", c.surname) AS name, GROUP_CONCAT(b.date) AS date, GROUP_CONCAT(b.endDate) AS enddate, GROUP_CONCAT(b.abo_id) AS abo_name, GROUP_CONCAT(b.id) AS bill_id
FROM customer c
LEFT JOIN bill b ON c.id = b.customer_id
GROUP BY name
) t
输出(JSON)
{
name: "Max Mustermann",
date: "2018-09-13,2018-09-27",
enddate: "2018-09-13,2018-09-28",
abo_name: "1,2",
bill_id: "23,27"
},
...
但现在我需要向abo_name属性添加更详细的信息,我需要输出完整的abo名称。我试图在查询中添加一个
INNER JOIN
,但是GROUP_CONCAT
不再工作。下面是一个例子:
查询
SELECT name, date, enddate, abo_name, bill_id
FROM (
SELECT CONCAT(c.firstname, " ", c.surname) AS name, GROUP_CONCAT(b.date) AS date, GROUP_CONCAT(b.endDate) AS enddate, GROUP_CONCAT(a.name) AS abo_name, GROUP_CONCAT(b.id) AS bill_id
FROM customer c
LEFT JOIN bill b ON c.id = b.customer_id
INNER JOIN abo a ON b.abo_id = a.id
GROUP BY name
) t
输出(JSON)
{
name: "Max Mustermann",
date: "2018-09-13",
enddate: "2018-09-13",
abo_name: "Einzelstunde",
bill_id: "23"
},
{
name: "Max Mustermann",
date: "2018-09-27",
enddate: "2018-09-28",
abo_name: "Schnupperstunde",
bill_id: "27"
},
如您所见,数据不一致,创建了两个对象。有人知道为什么会这样吗?
谢谢你的时间和帮助!
最佳答案
abo
有一个名为name的列。按表达式聚合或使用其他别名:
SELECT CONCAT(c.firstname, ' ', c.surname) AS new_name, GROUP_CONCAT(b.date) AS date, GROUP_CONCAT(b.endDate) AS enddate, GROUP_CONCAT(a.name) AS abo_name, GROUP_CONCAT(b.id) AS bill_id
FROM customer c LEFT JOIN
bill b
ON c.id = b.customer_id INNER JOIN
abo a
ON b.abo_id = a.id
GROUP BY new_name