SQL:如何根据第一张表中两列的ID从第二张表中获取数据?

时间:2018-11-17 03:59:50

标签: sql

enter image description here

我需要从第二个表(站)中获取相应的站名,以作为第一个表(行程)中的起始站ID和结束站ID。如何编写条件以将id与对应的名称匹配(请参见下面的查询)?

select 
    tp.id as Trip ID, st.station_name as Start Station, 
    st.station_name as End Station, en.entity_type as Subscriber Type 
from
    escooter_trips tp, escooter_stations st, escooter_entity en
where
    tp.start_station_id = st.id, 
    tp.end_station_id = st.id,
    tp.entity_id = en.id;

2 个答案:

答案 0 :(得分:1)

您必须加入escooter_stations 2次。

select  tp.id as Trip ID,
        st_start.station_name as Start Station,
        st_end.station_name as End Station,
        en.entity_type as Subscriber Type 

from    escooter_trips tp
        left join escooter_stations st_start on tp.start_station_id = st_start.id
        left join escooter_stations st_end on tp.end_station_id = st_end.id
        left join escooter_entity en on tp.entity_id = en.id;

答案 1 :(得分:1)

您将需要使用左外部联接2次,一次用于开始,一次用于结束,如下所示:

select et.id,es_start.station_name as [StartStationName],es_end.station_name as [EndStationName] 
from escooter_trips et
left outer join escooter_stations es_start on es.id = et.start_station_id
left outer join escooter_stations es_end on es.id = et.end_station_id