繁体   English   中英

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

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

在此处输入图片说明

我需要从第二个表(站点)中获取相应的站点名称,以作为第一个表(行程)中的起始站点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;

您必须加入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;

您将需要使用左外部联接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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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