Sql 使用自连接编写查询
已给出别名,用于区分表的两个副本。 如何将以下三个查询合并为一个?。我需要使用这些数据创建一个菜单。分层数据结构,例如国家->州->城市,如下所示 以下是表中的列:Sql 使用自连接编写查询,sql,sql-server-2008,Sql,Sql Server 2008,已给出别名,用于区分表的两个副本。 如何将以下三个查询合并为一个?。我需要使用这些数据创建一个菜单。分层数据结构,例如国家->州->城市,如下所示 以下是表中的列: [ID] ,[Type] ,[ParentID] ,[Title] ,[Name] ,[ZoneName] ,[TemplateKey] ,[TranslationKey]
[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,首页,1,假日,5531,StorefrontPage,810,加拿大,/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,加拿大,6132,ImportedPage,55312014特别优惠,/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,温哥华,6365,进口页,5542,阿拉斯加邮轮和温哥华住宿,/1/810/5531/
5542,StorefrontPage,5531,温哥华,6368,ImportedPage,5542,Best Western Plus Sands Hotel,/1/810/5531/这就是您要找的吗
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
子句中的独立逻辑组合在一起(在执行显式连接之后)。您可以Union all
将它们组合在一起-作为一个条件,您需要所有这3个查询返回相同数量的列。