[英]Nested select statement in mysql
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.
我正在尝试编写一条sql select语句,该语句将在一行中返回消息和所有引用该消息的注释。 Is there a way to do that in mysql?
有没有办法在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.
注释具有消息ID,它是与消息ID相关的外键。 Here is my ERD diagram
这是我的ERD图
You could use the group_concat
function: 您可以使用
group_concat
函数:
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
You should use group_concat and for group_concat you need group by 您应该使用group_concat,对于group_concat,您需要分组依据
SELECT message, GROUP_CONCAT(comment SEPARATOR ';') as comments
FROM messages
JOIN comments ON messages .id = comments .message_id
GROUP By message
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.