sql组\u concat不使用2表联接

lnlaulya  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(305)

我有一个查询正在按预期工作:
查询

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\u 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"
},

如您所见,数据没有连接,创建了两个对象。有人知道为什么会这样吗?
谢谢你的时间和帮助!

kcwpcxri

kcwpcxri1#

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

相关问题