Reputation: 1484
Here is the simplified schema:
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`)
);
How can I simply get the free space for each housing ?
I tried the following query:
select housing.Id, housing.Capacity - count(person.Id)
from housing, person
where person.HousingId = housing.Id
group by housing.Id
But it works only for housing having at least one person, not for empty ones.
Thanks for your help !
Upvotes: 1
Views: 3114
Reputation: 6732
Use a outer join
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
Upvotes: 4