开发者

Left Join two columns with the same type of data, different values

In my table I have two columns, cars.station1_id and cars.station2_id. These columns contain an ID number referencing stations.id.

I need to take the two ID's and retrieve stations.name for each of them.

How do I do this?

开发者_如何学Go

This is my code to join one column:

SELECT station1_id, station2_id FROM cars

LEFT JOIN stations

ON stations.id = cars.station_id


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


The key is to use a different alias each time.
s1 and s2 in this case:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜