我有三张桌子;公寓(apartmentnr,floor,apartmenttype),楼层(floornr,house),房子(housenr,地址)
现在,我想展示所有公寓类型(1-4)公寓的住宅和地址,使用“不存在”。
请帮我提一下如何做到这一点!
答案 0 :(得分:3)
正如@onedaywhen提示的那样,not exists
对于这项任务非常重要,count distinct
提供了更精简的语法(性能问题在他指出的文章中提到):
SELECT House.adress
FROM House
JOIN Floor ON (House.housenr=Floor.house)
JOIN Apartment ON (Floor.floornr=Apartment.floor)
GROUP BY House.housenr
HAVING COUNT(DISTINCT Apartment.apartmenttype)=4
基本上说“显示有4种不同类型公寓的房屋[[sic]]”。正如其他人所暗示的那样,强制使用not exists
的唯一理由就是家庭作业......
答案 1 :(得分:1)
那么你想用Chris Dates的方法,而不是那个受欢迎的Joe Celko?如果你不确定,这里讨论两种方法:
答案 2 :(得分:0)
如果我理解你的关系,你可以这样做。请记住,您可以使用表格的别名来使其更容易阅读,我只是让它们保持清晰,以便清楚我正在做什么。
Select House.hoursenr, address
inner join Floor on House.housenr = Floor.house
inner join Apartment on Apartment.floor = Floor.floornr
where Apartment.apartmenttype in (1,2,3,4)
我认为你的某些实体关系在表定义中是错误的。
答案 3 :(得分:0)
给出这样的结构:
ID 地址
ID HouseID
标识 FloorId ApartmentType
我认为这会解决问题:
SELECT H.ID FROM Houses H JOIN Floors F ON H.Id = F.HouseId JOIN Apartments A on F.Id = A.FloorId AND A.ApartmentType = 1 AND H.Id IN
(SELECT H.ID FROM Houses H JOIN Floors F ON H.Id = F.HouseId JOIN Apartments A on F.Id = A.FloorId AND A.ApartmentType = 2) AND H.Id IN
(SELECT H.ID FROM Houses H JOIN Floors F ON H.Id = F.HouseId JOIN Apartments A on F.Id = A.FloorId AND A.ApartmentType = 3) AND H.Id IN
(SELECT H.ID FROM Houses H JOIN Floors F ON H.Id = F.HouseId JOIN Apartments A on F.Id = A.FloorId AND A.ApartmentType = 4)
在英语中,它意味着,给我一套所有房屋,其中1型公寓也属于2套公寓的房屋......等等。