希望这有助于作为方法:
CREATE TABLE [dbo].[messages](
[id] [int] NOT NULL,
[replyto] [int] NOT NULL,
[title] [nvarchar](max) NULL,
[body] [nvarchar](max) NULL,
[created_at] [datetime] NULL
) ON [PRIMARY]
然后选择这样的数据:
WITH Children (id, replyto, title, body, created_at) AS (
SELECT id, replyto, title, body, created_at
FROM [messages]
WHERE replyto = -1 -- all msg from root
UNION ALL
SELECT b.id, b.replyto, b.title, b.body, b.created_at
FROM Children a, [messages] b
WHERE a.id = b.replyto
)
SELECT id, replyto, title, body, created_at FROM Children
在我的示例回复中不可为空,因此我将 -1 定义为根消息。如果您想要特定消息 + 他们的孩子,那么您修改第一个 SELECT 语句。