简体   繁体   中英

How can I combine these 2 queries to one?

I have these two queries where I'm not able to combine them properly.

I want to get comments for a particular discussion and every comment can have multiple images which are stored in the images table.

SELECT c.CommentID, c.Body, u.Name
FROM Comments c
JOIN User u ON u.UserID = c.InsertUserID
WHERE c.DiscussionID = 1

SELECT Path
FROM Images
WHERE commentID = ?

This is what I came up with, but it's not working:

SELECT c.CommentID, c.Body, u.Name, i.Path
FROM Comments c
JOIN User u ON u.UserID = c.InsertUserID
LEFT JOIN Images i ON c.CommentID = i.ForeignID
WHERE c.DiscussionID = 1
SELECT c.CommentID, c.Body, u.Name, (SELECT GROUP_CONCAT(Path SEPARATOR "\n") FROM Images i WHERE i.commentID = c.CommentID) as 'images'
FROM Comments c
JOIN User u ON u.UserID = c.InsertUserID
WHERE c.DiscussionID = 1

You'll receive one row for each comment and all of comment images will be in 'images' field. Images will be separated by newline ( "\\n" ) character.

JOIN version as requested:

SELECT c.CommentID, c.Body, NAME, GROUP_CONCAT(Path SEPARATOR "\n") AS 'images'
FROM Comments c
LEFT JOIN Images i ON(i.commentID = c.CommentID)
WHERE   c.DiscussionID = 1
GROUP BY c.CommentID

Note that JOIN version might not be as efficient as the subquery version. The GROUP BY phase in the first query happens on subquery level whereas in case of second query it happens after all rows have been already joined. Of course query optimizer might do some magic here and they might have the same cost.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM