内部连接到同一个表两次(ALIASES)

时间:2015-03-20 22:06:10

标签: mysql sql inner-join

我的内部联接存在问题,这些是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会显示name of city depo的{​​{1}}

references CITY.city_id将显示manufacturer_city_name name of city的{​​{1}}

感谢

1 个答案:

答案 0 :(得分:0)

你需要一个左外连接:

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