问题
i have a table i would like to add to my current Join:
Table (report_images) include a report_id and a image_path.
Reference: Mysql Inner Join and Group By repeating row
How it is now:
["text": "My first report", user: [{"display_name": "Cyclops", "photo_url": "CYCLOPS_IMAGE.png"}], comments: [{"text": "Great Report", display_name: "Xavier"}, {"text": "Bad Report", display_name: "Logan"}, {"text": "Thanks for the feedback", display_name: "Cyclops"}]]
What i expect:
["text": "My first report", user: [{"display_name": "Cyclops", "photo_url": "CYCLOPS_IMAGE.png"}], images: [{"image_path": "dog.png"}, {"image_path": "cat.png"}], totalComments: 3, comments: [{"text": "Great Report", display_name: "Xavier"}, {"text": "Bad Report", display_name: "Logan"}, {"text": "Thanks for the feedback", display_name: "Cyclops"}]]
Current code:
SELECT report.text,
Json_arrayagg(Json_object('display_name', users.display_name, 'photo_url'
,
users.photo_url)) AS USER,
rc.COMMENTS
FROM report
INNER JOIN users ON users.id = report.user_id
LEFT JOIN (
SELECT COUNT(*) AS totalComments, report_id,
Json_arrayagg(Json_object('text', report_comments.text, 'display_name',
users.display_name)) AS COMMENTS
FROM report_comments
JOIN users ON report_comments.user_id = users.id
GROUP BY report_id
) rc ON rc.report_id = report.id
WHERE report.user_id = 4
GROUP BY report.id, rc.COMMENTS
回答1:
Here's a CTE-based solution which aggregates the user, image and comment information in CTEs and then joins all those CTEs to the report table to collect all the data together:
WITH user AS (
SELECT id, JSON_ARRAYAGG(JSON_OBJECT('display_name', u.display_name, 'photo_url', u.photo_url)) AS user
FROM users u
WHERE id = 4
),
img AS (
SELECT report_id, JSON_ARRAYAGG(JSON_OBJECT('image_path', image_path)) AS images
FROM report_images
GROUP BY report_id
),
cmt AS (
SELECT report_id,
JSON_ARRAYAGG(JSON_OBJECT('text', rc.text, 'display_name', u.display_name)) AS comments,
COUNT(*) AS totalcomments
FROM report_comments rc
JOIN users u ON rc.user_id = u.id
GROUP BY report_id
)
SELECT r.text,
u.user,
img.images,
cmt.totalcomments,
cmt.comments
FROM report r
JOIN user u ON u.id = r.user_id
LEFT JOIN img ON img.report_id = r.id
LEFT JOIN cmt ON cmt.report_id = r.id
Demo on dbfiddle
来源:https://stackoverflow.com/questions/65546040/mysql-add-another-table-into-join