1

这是简化的架构:

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 

但它只适用于至少有一个人的住房,不适用于空置的住房。

谢谢你的帮助 !

4

1 回答 1

4

使用外连接

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
于 2013-01-06T21:07:07.933 回答