2010-06-22 119 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 
相關問題