[英]Mysql select rows from multiple tables in specific order
我在mysql数据库中有2个表(“评论”和“回复”)
它们具有以下架构:
comments: id,userId,text
replies: id,userId,commentId,text
我需要一个mysql查询,它将从注释表中获取所有注释,并且在每个注释之后,都会从答复表中获取相应的答复...
因此,如果我们[comment 1] and [comment 2] in the comments table, and [reply 1] (to comment 1) and [reply 2] (to comment2)
具有: [comment 1] and [comment 2] in the comments table, and [reply 1] (to comment 1) and [reply 2] (to comment2)
然后它将返回:
[comment 1]
[reply 1]
[comment 2]
[reply 2]
您将需要将两个表连接起来,然后基于commentID和ReplyID进行多个答复的排序。
在以下内容中,我为原始评论添加了一个虚拟的ReplyID 0。 这些表使用UNION ALL连接。 请注意,我已将评论表和回复ID的原始ID列重命名,以免冲突。
SELECT id commentID, userID, text, 0 replyID FROM test.comments
UNION ALL
SELECT commentID, userID, text, id replyID FROM test.replies
ORDER BY commentID, replyID;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.