2010-06-22 120 views
2

在我的表中,我有两列cars.station1_idcars.station2_id。这些列包含引用stations.id的ID号。左连接具有相同类型数据的两列,不同的值

我需要采取两个ID和检索stations.name为他们每个人。

我该怎么做?

这是我的代码加入一列:

SELECT station1_id, station2_id FROM cars
LEFT JOIN stations
ON stations.id = cars.station_id

+0

什么是cases.station_id – 2010-06-22 18:46:18

+0

可以填充一辆车同时记录station_id引用,或将它永远只能是其中之一? – 2010-06-22 18:50:25

+0

@ d03boy哎呀,我的意思是'cars.station_id' – bobby 2010-06-22 18:52:19

回答

3
SELECT a.name, b.name 
FROM cars 
LEFT JOIN stations a ON a.id = station_id 
LEFT JOIN stations b ON b.id = station2_id 
2

关键是每次使用不同的别名。
s1s2在这种情况下:

SELECT station1_id, station2_id 
    FROM cars 
     LEFT JOIN stations s1 
     ON s1.id = cars.station1_id 
     LEFT JOIN stations s2 
     ON s1.id = cars.station2_id 
相关问题