内部加入相同的 table 两次(别名)

the inner join to the same table twice(ALIASES)

我的内部联接有问题,这些是我的表 FKPK

TABLE CITY
city_id (PK)
city_name
state

TABLE DEPOT
dep_id (PK)
capacity
city_id (FK) references CiTy

TABLE MANUFACTURER
manu_id (PK)
manu_name
city_id (FK) references city

所以我只想让结果看起来像这样:

DEPOT_CITY_name(references from city_id)MANUFACTURER_CITY_name(references from city_id)

所以 depot_city_name 将显示来自 depo (references CITY.city_id)

name of city

manufacturer_city_name 将显示来自 manufacturer (references CITY.city_id)

name of city

谢谢

您需要一个左外连接:

select c.city_id, d.depo_id, m.manu_id,c.city_name
from city c
left outer join depo d on c.city_id=d.city_id
left outer join manufacturer m on c.city_id=m.city_id

编辑: 如果要将 depo 和制造商的城市名称分开,请使用:

select c.city_id, d.depo_id, m.manu_id,
case 
when  d.depo_id is null then null else c.city_name end DEPOT_CITY_name,
case 
when m.manu_id is null then null else c.city_name end manufacturer_city_name 
from city c
left outer join depo d on c.city_id=d.city_id
left outer join manufacturer m on c.city_id=m.city_id