在SQL中包含ParentId记录

时间:2013-08-02 13:25:41

标签: sql sql-server-2008 sql-server-2005 sql-server-2008-r2

我的下表包含应用程序功能列表:

ApplicationFeature

Id Name MenuId

值为:

1 PatientSearch 2

ApplicationMenu

Id DisplayText Url ParentMenuId

1 Patient patient NULL

2 PatientSearch search 1

我需要获取菜单信息以及功能。到目前为止,我只能获得映射菜单,但也不能获取父菜单项。

SELECT
AF.Name, AF.Id As FeatureId, AM.Id AS MenuId, AM.DisplayText,AM.Url
FROM 
ApplicationFeature AF 
INNER JOIN ApplicationMeny AM ON AF.MenuId=AM.Id 

我的结果仅显示PatientSearch菜单详细信息,但不包括患者菜单。

如何让查询也检索父菜单细节?

修改:

我需要使用Parent构建菜单。如果父菜单有另一个父菜单,我也需要包含该菜单。

-- Parent(Id=2)

  --- SubParent(Id=10 & ParentId=2)

    ----ActualMenuMappedwithFeature(Id=30 & ParentId=10)

在上面的例子中,我想要菜单ID 30, 10, 2

的结果

2 个答案:

答案 0 :(得分:1)

嗯,很难说,你想得到什么。但是,如果您只想获取一个父级,则可以执行其他连接

select
    AF.Name, AF.Id As FeatureId,
    AM.Id as MenuId, AM.DisplayText, AM.Url,
    AMP.Id as ParentMenuId, AMP.DisplayText as ParentDisplayText, AM.Url as ParentUrl
from ApplicationFeature as AF
    inner join ApplicationMenu as AM on AM.Id = AF.MenuId
    left outer join ApplicationMenu as AMP on AMP.Id = AM.ParentMenuId

如果您希望让所有家长到达顶部,请澄清所需的输出格式
修改

declare @FeatureId = ???

;with CTE as (
  select
     AF.Name, AF.Id As FeatureId,
     AM.Id as MenuId, AM.DisplayText, AM.Url,
     AM.ParentId
  from ApplicationFeature as AF
     inner join ApplicationMenu as AM on AM.Id = AF.MenuId
  where AF.Id = @FeatureId

  union all

  select
     null as Name, null as FeatureId,
     AM.Id as MenuId, AM.DisplayText, AM.Url,
     AM.ParentId
  from ApplicationMenu as AM
     inner join CTE as C on C.ParentId = AM.Id
)
select * from CTE

答案 1 :(得分:-1)

<强>已更新

您需要第二次加入才能获得父

SELECT AF.ID,
AM.DisplayText as child,
Parent.DisplayText as parent
FROM ApplicationFeature AF 
LEFT JOIN ApplicationMenu AM ON AF.MenuId = AM.Id 
LEFT JOIN ApplicationMenu as Parent on AM.ParentMenuId = Parent.ID

<强> SQLFiddle

<强> RESULT

enter image description here