1

I have two tables a messages and a comments sections. A messages can have many comments, but a comments can only have one message. I am trying to write a sql select statement that would return the message and all comments referring to that message in one row. Is there a way to do that in mysql? How would I go about it. The comments has a message id which is a foreign key that relates to the id of messages. Here is my ERD diagram

enter image description here

2 Answers 2

1

You should use group_concat and for group_concat you need group by

SELECT message, GROUP_CONCAT(comment SEPARATOR ';') as  comments
FROM   messages 
JOIN   comments  ON messages .id = comments  .message_id
GROUP By message
Sign up to request clarification or add additional context in comments.

Comments

1

You could use the group_concat function:

SELECT   message, GROUP_CONCAT(comment SEPARATOR ';') AS all_comments
FROM     messages m
JOIN     comments c ON m.id = c.message_id
GROUP BY m.id, message

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.