[英]Mysql join tables without repeating rows which belong to same row
幾個小時以來,我一直試圖弄清楚這一點。 但沒有運氣。
這很有效,但是我遇到了這些問題。 例如,如果同一份報告有超過 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
如果您按報告分組並將 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
請參閱演示。
結果:
> text | User_ID | User_Name | id | comment
> :-------------- | :------ | :----------- | :- | :----------------------
> My first report | 1,2 | Xavier,Logan | 15 | Bad Report,Great Report
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.