Mysql 连接表而不重复属于同一行的行

时间:2020-12-27 16:54:38

标签: mysql join aggregate-functions

我几个小时以来一直在努力解决这个问题。但没有运气。

这很好用,但是我遇到了这些问题。例如,如果同一报告有超过 1 条评论,那么这将创建新行,而不是将同一行的评论与报告合并。

现在怎么样了:

{"text":"My first report","comment":"Great Report","display_name":"Xavier"},
{"text":"My First report","comment":"Do you call this a report?","display_name":"Logan"}

我想要的样子:

{"text":"My first report","comments":[{comment: "Great Report","display_name":"Xavier"}, {comment: "Do you call this a report?","display_name":"Logan"}],

当前设置

Report
ID | User_ID | TEXT |
15   3        My first report

Users
ID | DISPLAY_NAME |
1   Xavier
2   Logan
3   Cyclops

Report_Comments
ID | User_ID | Report_ID | TEXT as comment |
3   1          15         Great Report
4   2          15         Bad Report

应该如何:

Report_Comments
ID | User_ID | Report_ID | TEXT as comment |
3   1, 2          15         Great Report, Bad Report
SELECT report.text, 
       report_comments.text AS comment, 
       users.display_name 
FROM   report 
       LEFT JOIN users 
              ON users.id = report.user_id 
       LEFT JOIN report_comments 
              ON report_comments.report_id = report.id 
WHERE  report.user_id = :userId 

1 个答案:

答案 0 :(得分:1)

如果您按报告分组并使用 GROUP_CONCAT() 作为用户 ID 和名称以及评论文本,您就可以做到:

SELECT r.text, 
       GROUP_CONCAT(c.user_id ORDER BY c.ID) AS User_ID,
       GROUP_CONCAT(u.display_name ORDER BY c.ID) AS User_Name,
       r.id,
       GROUP_CONCAT(c.text) AS comment
FROM   report r
       LEFT JOIN report_comments c ON c.report_id = r.id
       LEFT JOIN users u ON u.id = c.user_id 
-- WHERE  report.user_id = :userId       
GROUP BY r.id, r.text

参见demo
结果:

> text            | User_ID | User_Name    | id | comment                
> :-------------- | :------ | :----------- | :- | :----------------------
> My first report | 1,2     | Xavier,Logan | 15 | Bad Report,Great Report
相关问题