Mysql select 行来自多个表的特定顺序
Mysql select rows from multiple tables in specific order
我在 mysql 数据库中有 2 个 table("comments" 和 "replies")
他们有架构:
comments: id,userId,text
replies: id,userId,commentId,text
我需要一个 mysql 查询,它将从评论 table 中获取所有评论,并且在每个评论之后,回复 table 中的相应回复...
所以如果我们有: [comment 1] and [comment 2] in the comments table, and [reply 1] (to comment 1) and [reply 2] (to comment2)
在回复中 table
那么它会 return:
[comment 1]
[reply 1]
[comment 2]
[reply 2]
您需要加入两个 table,然后根据 commentID 和 replyID 对多个回复进行排序。
在下文中,我为原始评论添加了一个虚拟的 replyID 0。 tables 使用 UNION ALL 连接。请注意,我已经重命名了评论 table 和回复 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;
我在 mysql 数据库中有 2 个 table("comments" 和 "replies")
他们有架构:
comments: id,userId,text
replies: id,userId,commentId,text
我需要一个 mysql 查询,它将从评论 table 中获取所有评论,并且在每个评论之后,回复 table 中的相应回复...
所以如果我们有: [comment 1] and [comment 2] in the comments table, and [reply 1] (to comment 1) and [reply 2] (to comment2)
在回复中 table
那么它会 return:
[comment 1]
[reply 1]
[comment 2]
[reply 2]
您需要加入两个 table,然后根据 commentID 和 replyID 对多个回复进行排序。
在下文中,我为原始评论添加了一个虚拟的 replyID 0。 tables 使用 UNION ALL 连接。请注意,我已经重命名了评论 table 和回复 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;