简体   繁体   English

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

[英]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). 我需要从第二个表(站点)中获取相应的站点名称,以作为第一个表(行程)中的起始站点ID和结束站点ID。 How to write the condition to match id with its corresponding name(see query below)? 如何编写条件以将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;

You have to join escooter_stations 2 times. 您必须加入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;

You will need to use left outer join 2 times, one for start, one for end, like below: 您将需要使用左外部联接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.

相关问题 如何在SQL中基于同一表的两列获取数据 - How to get data based on two columns from same table in SQL SQL根据第一个表的ID(Key)从两个表中检索数据 - SQL retrieve data from two table based on the ID(Key) of the first table 根据第一个表中的值从第二个表中获取和回显数据 - Fetch and echo data from second table based on value inside first table 根据同一表中的多列从表中获取数据 - Fetch data from table based on multiple columns from same table SQL 连接表并根据数据将第二个表显示为两列 - SQL Joining tables and display second table as two columns based on data 根据第一个ID从第二个表中选择行 - Select Rows From Second Table Based On id From First SQL根据第二个表中的搜索条件从第一个表中检索数据 - SQL Retrieve data from first table based on search criteria in second table SQL:是否可以使用自动生成的 id output 从第一个表同时插入到第二个表中 - SQL: Is it possible to insert into two tables at the same time with autogenerated id output from first table into second 当第二个表中没有数据时,如何从第一个表中获取表 - how to get table from first table when data is not there in second table 根据来自第一个表的第二个数字值联接两个表 - Joining two tables on based on second number value from first table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM