1

我的数据库具有以下结构:

每个地区 ( CountryStates) 可以有许多城市 ( Areas)。每个都Area可以有许多旅游景点或兴趣点 ( POIs)。我想获取每个地区有多少个地区和景点的列表。如果没有,我想显示 0。

这是我的查询:

SELECT Tab1.Reg AS Reg, CountAreas, CountPois
FROM
(SELECT 
        c.Name AS Reg, 
        COUNT(a.Id) AS CountAreas
FROM  
       CountryStates as c LEFT JOIN
       Areas AS a ON a.CountryStates_Id = c.Id
GROUP BY c.Name 
) as Tab1 left join
(SELECT 
        c1.Name AS Reg, 
        COUNT(p.Id) AS CountPois
FROM  
       CountryStates as c1 LEFT JOIN
       Areas AS a ON a.CountryStates_Id = c1.Id LEFT JOIN
       POIs AS p ON a.Id = p.Areas_Id
GROUP BY c1.Name 

) as Tab2 on Tab1.Reg = Tab2.Reg

我怎样才能在一个查询中进行此查询SELECT

4

1 回答 1

1

此查询返回相同的结果:

SELECT c.Name AS Reg, 
        COUNT(DISTINCT(a.Id)) AS CountAreas,
        COUNT(p.Id) AS CountPois
FROM CountryStates as c 
    LEFT JOIN Areas as a ON a.CountryStates_Id = c.Id
    LEFT JOIN POIs AS p ON a.Id = p.Areas_Id
GROUP BY c.Name 
于 2012-04-27T11:09:53.670 回答