来自两个表的sql视图

时间:2018-12-21 17:01:56

标签: sql view

我有一个具有主键-NID的Neighbourhood表和一个具有外键NeighborhoodID的Apartment表。 我如何创建一个视图,以显示每个邻域中有多少套公寓。 谢谢!

2 个答案:

答案 0 :(得分:0)

我将加入邻域ID上的表,对其进行分组并计算行数:

CREATE OR REPLACE VIEW neighbourhood_apartments AS
SELECT   n.name, COUNT(*)
FROM     neighbourhood n
JOIN     apartment a ON n.nid = a.neightbourhoodid
GROUP BY n.name

答案 1 :(得分:0)

对于neighborhood中的每个id,计算apartment中与neighborhoodid匹配的行:

   SELECT 
     neighborhood.id,
     neighborhood.name, 
     (SELECT COUNT(*) FROM apartment AS a WHERE a.neighborhoodid = n.id) AS counter  
   FROM
     neighborhood AS n