从 mysql 版本 15.1 中的多个表进行分组连接

Group concatenate from multiple tables in mysql Ver 15.1

我有多个 table,其中 table 1 包含主 ID 键。我正在根据 id 连接所有 table。但这并没有给我想要的输出。

 Table1
id account type date
1 234w R 2020-01-01
2 567 FD 2020-05-07
3 678gh FD 2020-09-10

Table2
id designation
2 customer
3 employee
3 manager

Table3
id state
1 UP
2 AP
3 UK

这是我试过的

SELECT CONCAT(`account`,"/",`type`,"/",`date`),
GROUP_CONCAT(Table2.designation SEPARATOR "/") AS t2,
GROUP_CONCAT(Table3.state SEPARATOR "/") AS t3,
FROM Table1 t1
LEFT JOIN table1 ON t1.id=t2.id
LEFT JOIN table1 ON t1.id=t3.id
GROUP BY t1.id

Expected output
234w/R/2020-01-01 NULL UP
567/FD/2020-05-07 CUSTOMER AP
678gh/FD/2020-09-10 EMPLOYEE/MANAGER UK

您必须修复联接。
还对第一列使用像 MAX() 这样的聚合函数,因为它不包含在 GROUP BY:

SELECT MAX(CONCAT(account,"/",type,"/",date)) AS col1,
       GROUP_CONCAT(t2.designation SEPARATOR "/") AS col2,
       GROUP_CONCAT(DISTINCT t3.state SEPARATOR "/") AS col3
FROM Table1 t1
LEFT JOIN Table2 t2 ON t1.id=t2.id
LEFT JOIN Table3 t3 ON t1.id=t3.id
GROUP BY t1.id

在第二个 GROUP_CONCAT() 中,我使用 DISTINCT 因为从您的预期结果来看,您似乎不想要重复项。
您也可以在第一个GROUP_CONCAT()
.

中使用它

参见demo
结果:

> col1                         | col2             | col3
> :--------------------------- | :--------------- | :---
> 234w/R/2020-01-01 00:00:00   | null             | UP  
> 567/FD/2020-05-07 00:00:00   | customer         | AP  
> 678gh/FD/2020-09-10 00:00:00 | employee/manager | UK 

据我了解你的问题,两个表中可能有多个匹配项。在那种情况下,我会推荐预聚合。我发现用子查询很容易表达这一点:

select concat_ws('/', account, type, date) as res,
    (select group_concat(designation separator '/') from table2 t2 where t2.id = t1.id) as designations,
    (select group_concat(state       separator '/') from table3 t3 there t3.id = t1.id) as states
from table1 t1

请注意 concat_ws() 可以方便地缩短第一个 concat()