[英]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.