2013-01-06 59 views
1

這裏一個SQL計數簡化架構:如何執行基於外鍵

CREATE TABLE IF NOT EXISTS `person` (
    `Id` int(11) NOT NULL AUTO_INCREMENT, 
    `HousingId` int(11) NOT NULL, 
    PRIMARY KEY (`Id`) 
); 

CREATE TABLE IF NOT EXISTS `housing` (
    `Id` int(11) NOT NULL AUTO_INCREMENT, 
    `Capacity` int(11) NOT NULL, 
    PRIMARY KEY (`Id`) 
); 

我怎麼能簡單地獲得每個房屋的自由空間?

我嘗試以下查詢:

select housing.Id, housing.Capacity - count(person.Id) 
from housing, person 
where person.HousingId = housing.Id 
group by housing.Id 

但它僅適用於具有至少一個人,而不是空的住房。

感謝您的幫助!

+1

其SQL?MySQL和MSSQL,sqllite –

+0

我使用MySQL,但問題應該是有效無論DB系統。 –

+0

嘗試在SQLfiddle中構建該模式來測試它,然後告訴我... –

回答

3

使用外部聯接

select housing.Id, housing.Capacity - count(person.Id) 
from housing 
LEFT OUTER JOIN person ON person.HousingId = housing.Id 
group by housing.Id, housing.Capacity 
+0

不工作,對不起 –

+0

不工作如何? – BellevueBob

+0

再試一次。編輯。 –