mysql版本15.1中的多个表的组连接



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

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

根据我的理解,两个表中可能有多个匹配项。在这种情况下,我建议进行预聚合。我发现用子查询来表达这一点很容易:

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

注意,CCD_ 1对于缩短第一个CCD_。

您必须修复联接
还要对第一列使用类似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()中使用它

请参阅演示
结果:

> 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 

最新更新