使用SELF JOIN编写查询

时间:2014-05-25 12:03:48

标签: sql sql-server-2008

使用别名来区分表的两个副本。 如何将以下三个查询合并为一个?我需要使用这些数据创建一个菜单。分层数据结构如下面的例如Country - >州 - >援引。

以下是表格中的列:

           [ID]
          ,[Type]
          ,[ParentID]
          ,[Title]
          ,[Name]
          ,[ZoneName]
          ,[TemplateKey]
          ,[TranslationKey]
          ,[Created]
          ,[Updated]
          ,[Published]
          ,[Expires]
          ,[SortOrder]
          ,[Visible]
          ,[VersionOfID]
          ,[SavedBy]
          ,[AncestralTrail]
          ,[VersionIndex]
          ,[State]
          ,[ChildState]
          ,[AlteredPermissions]

SELECT a.[ID],a.[Type],a.[ParentID],a.[Title],b.[ID],b. [Type],b.[ParentID],b.[Title], a.[AncestralTrail] 
FROM [n2Item] a, [n2Item] b
WHERE a.[ID] = b.[ParentID] AND a.Title = 'Holidays'  AND b.[Type] = 'StorefrontPage' 
ORDER BY b.[Title] ,A.[ParentID],a.[SortOrder];

结果: 810,HomePage,1,Holidays,5531,StorefrontPage,810,Canada,/ 1 /

SELECT a.[ID],a.[Type],a.[ParentID],a.[Title],b.[ID],b. [Type],b.[ParentID],b.[Title], a.[AncestralTrail] 
FROM [n2Item] a, [n2Item] b 
WHERE a.[id] = b.[ParentID] AND a.Title = 'Canada'  
ORDER BY b.[Title] ,A.[ParentID],a.[SortOrder];

结果: 5531,StorefrontPage,810,Canada,6132,ImportedPage,5531,2014特别优惠,/ 1/810 /

SELECT a.[ID],a.[Type],a.[ParentID],a.[Title],b.[ID],b. [Type],b.[ParentID],b.[Title], a.[AncestralTrail] 
FROM [n2Item] a, [n2Item] b 
WHERE a.[id] = b.[ParentID] AND a.Title = 'Vancouver'  
ORDER BY b.[Title] ,A.[ParentID],a.[SortOrder];

结果: 5542,StorefrontPage,5531,Vancouver,6365,ImportedPage,5542,Alaska Cruise and Vancouver Stay,/ 1/810/5531 / 5542,StorefrontPage,5531,Vancouver,6368,ImportedPage,5542,Best Western Plus Sands Hotel,/ 1/810/5531 /

1 个答案:

答案 0 :(得分:0)

这是你在找什么?

SELECT a.[ID], a.[Type], a.[ParentID], a.[Title], b.[ID], b.[Type], b.[ParentID], b.[Title],
       a.[AncestralTrail] 
FROM [n2Item] a JOIN
     [n2Item] b
     ON a.[ID] = b.[ParentID]
WHERE a.Title IN ('Canada', 'Vancouver') OR
      (a.Title = 'Holidays' AND b.[Type] = 'StorefrontPage')
ORDER BY b.[Title] ,A.[ParentID],a.[SortOrder];

这只是组合了WHERE子句中的单独逻辑(在进行显式连接之后)。