内部加入两次在同一个表中

时间:2015-03-20 12:54:12

标签: mysql sql inner-join

我的内连接有问题,这些是我的FK和PK表

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(referencese from city_id), MANUFACTURER_CITY_name(references from city_id)

感谢

2 个答案:

答案 0 :(得分:1)

在from子句中使用不同的别名列出两次表。

这将为您提供不同的城市,一个用于制造商,一个用于仓库。

SELECT dc.city_name AS depot_city
,      mc.city_name AS manufacturer_city
FROM   DEPOT AS d
JOIN   CITY AS dc
    ON dc.city_id = d.city_id
JOIN   MANUFACTURER AS m
    ON m.some_column = d.some_column -- or however these tables relate
JOIN   CITY AS mc
    ON mc.city_id = m.city_id

答案 1 :(得分:0)

在cityid上做两个左连接:

select depot.city_id, Manufacturer.city_id from

depot  left join city on city.city_id = depot.city_id
       left join Manufacturer on Manufacturer.city_id = city.city_id