简体   繁体   English

MySQL从多个表中以特定顺序选择行

[英]Mysql select rows from multiple tables in specific order

I have 2 tables in a mysql database ("comments" and "replies") 我在mysql数据库中有2个表(“评论”和“回复”)

They have the schemas: 它们具有以下架构:

comments: id,userId,text
replies: id,userId,commentId,text

I need a mysql query that will fetch all comments from the comment table, and after each comment, the corresponding replies from the replies table... 我需要一个mysql查询,它将从注释表中获取所有注释,并且在每个注释之后,都会从答复表中获取相应的答复...

so if we had: [comment 1] and [comment 2] in the comments table, and [reply 1] (to comment 1) and [reply 2] (to comment2) in the replies table 因此,如果我们[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)

then it would return: 然后它将返回:

    [comment 1]
    [reply 1]
    [comment 2]
    [reply 2]

You would need to join the two tables & then order based on the commentID & replyID for multiple replies. 您将需要将两个表连接起来,然后基于commentID和ReplyID进行多个答复的排序。

In the following I have added a dummy replyID of 0 for the original comment. 在以下内容中,我为原始评论添加了一个虚拟的ReplyID 0。 The tables are joined using UNION ALL. 这些表使用UNION ALL连接。 Note that I have renamed the original id column of the comments table & reply id so they do not clash. 请注意,我已将评论表和回复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.

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