简体   繁体   中英

SQL : How to fetch data from second table based on ID from two columns in first table?

在此处输入图片说明

I need to fetch corresponding station name from second table (stations) for the start and end station id in first table(trips). How to write the condition to match id with its corresponding name(see query below)?

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;

You have to join escooter_stations 2 times.

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;

You will need to use left outer join 2 times, one for start, one for end, like below:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM