sql-server – 如何从两个不同的表中获取数据层次结构?

我有两个表TwitterStatus和twitterstatusDetails,

我有以下方式分别有数据.

这里在twitterstatus表中给出第4条记录,ts_StatusID“587573444633427968”是twitterstatus_Details表第3条记录的父级,其td_inReplyTostatusID值为“587573444633427968”,对于下一条记录,最近子记录的td_StatusID是具有该子级ts_StatusID值的twitterstatus表的父级ts_InreplytoStatusID字段,所以就像它是层次结构一样

如何根据子父关系从两个表中获取记录?

仍有任何疑虑,请在评论中提问.

谢谢.

最佳答案 我认为你正在寻找的是递归CTE来获得每个嵌套级别.

希望这能让你更接近你的目标.

--REPLACE @TwitterStatus and @twitterstatus_Details with your tablename.
;WITH CteTStatus
AS
(
    SELECT h.*, d.*, 0 as lvl
    FROM  @TwitterStatus AS h
    INNER JOIN @twitterstatus_Details AS d ON h.id_StatusID = d.td_InreplytoStatusID
    WHERE ts_StatusID = '587573444633427968'--WHERE CLAUSE TO GET ROOT PARENT
    UNION ALL -- UNION TO DIG INTO CHILD's
    SELECT h.*, d.*, lvl + 1 as lvl
    FROM  @TwitterStatus AS h
    INNER JOIN @twitterstatus_Details AS d ON h.id_StatusID = d.td_InreplytoStatusID
    INNER JOIN CteTStatus AS Parent ON h.ts_InreplytoStatusID = Parent.td_StatusID
)

SELECT *
FROM CteTStatus
点赞