[英]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.