SQL结果获取电子邮件线程

时间:2018-08-24 15:16:48

标签: sql hierarchical-data recursive-query

我有一个消息系统表。它存储典型的从(到)甚至大约(三向系统)和RepliedToID ...该消息可能是答复的消息的ID。每个消息可以有多个答复。它最终可以创建一条链接在一起的消息线程。

对于如何创建一个查询,该查询可以将具有ID的线程中的任何消息带入并检索该线程之前和之后的消息,我感到很困惑。

=============
MID   ReplyID   Message
1               First Message
2     1         Second Mess replied to #1
3     2         Third Mess replied to #2
4     2         Fourth Mess replied to #2
5     4         Fifth Mess replied to #4
=============

如果我只有一个MID,是否可以获取线程中所有消息的结果? (当然,由于MID是自动编号键,因此它们之间会混合各种消息)

1 个答案:

答案 0 :(得分:0)

使用下表和数据:

MID ReplyId Message       
1   0   First Message                       f
2   1   Second Mess replied to #1
3   2   Third Mess replied to #2
4   2   Fourth Mess replied to #2
5   4   Fifth Mess replied to #4
6   0   New thread
7   6   Reply to new thread
8   4   Reply to #4

如果您使用与此类似的SQL语句:

SELECT t1.MID, t1.Message, t2.ReplyID, t2.Message as Msg_Reply 
FROM test_table t1
CROSS JOIN test_table t2 ON t1.MID = t2.ReplyID
ORDER BY ReplyID

它为您提供了一张这样的桌子

MID Message                 ReplyID Msg_Reply
1   First Message               1   Second Mess replied to #1
2   Second Mess replied to #1   2   Third Mess replied to #2
2   Second Mess replied to #1   2   Fourth Mess replied to #2
4   Fourth Mess replied to #2   4   Fifth Mess replied to #4
4   Fourth Mess replied to #2   4   Reply to 4
6   New thread                  6   Reply to new thread

我想之后,您可以遍历这些数据并在线程之后显示它。