【问题标题】:Mysql join tables without repeating rows which belong to same rowMysql连接表而不重复属于同一行的行
【发布时间】:2021-04-04 15:59:18
【问题描述】:

我已经尝试了好几个小时来解决这个问题。但没有运气。

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

现在怎么样了:

{"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 

【问题讨论】:

  • ...联合 cmets... 怎么样?发布样本数据和预期结果以澄清。
  • 我已经更新了当前行为和预期结果的示例
  • 您将示例数据和预期结果显示为 json 对象,但您发布的查询以包含行和列的表格格式返回结果集。那么你想要的是哪一个?
  • 我发布的示例数据,当我使用 json_ecode 回显它时,它是如何在 php 文件中显示的。但我会像我发布的那样工作。
  • 正如我所说的,一个 sql 查询将返回行和列。您可以发布您的预期结果吗?

标签: mysql join aggregate-functions


【解决方案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

【讨论】:

  • 这很好用,但我的问题是。是否有可能实现我尝试使用 json 格式的方式?或者是另一个话题?
  • 这就是为什么我问你是否想要 json 格式的结果。您发布了一个与 json 无关的查询。如果您想要严格的 json 结果,请询问您提到的问题并发布所有相关代码。
  • 哦,我以为他们手牵手。我的错,但我学到了一些新东西。所以我很感激
猜你喜欢
  • 2017-01-01
  • 2012-03-28
  • 2018-06-19
  • 2018-12-04
  • 2021-12-05
  • 1970-01-01
  • 2015-06-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多