【问题标题】:Group concatenate from multiple tables in mysql Ver 15.1从 mysql Ver 15.1 中的多个表进行组连接
【发布时间】:2021-04-06 11:23:21
【问题描述】:

我有多个表,其中表 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

【问题讨论】:

  • mysql 2.7?你确定吗?
  • @forpas 版本 15。感谢您指出这一点。我想我仍然记得我的 python 版本。
  • 您接受最新答案有什么原因吗?

标签: mysql sql subquery left-join aggregate-functions


【解决方案1】:

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

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()

【讨论】:

    【解决方案2】:

    您必须修复连接。
    还要对第一列使用像 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 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 2014-02-07
      • 1970-01-01
      • 1970-01-01
      • 2016-01-04
      • 1970-01-01
      • 2020-03-23
      相关资源
      最近更新 更多