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