联接查询2个表

时间:2018-11-19 03:16:07

标签: sql join

我有2个表分别命名为portrate

Port has (id, country, name) 
rate has (id, description, rate_min, rate_max, Origin_id, Destination_id). 

我需要创建一个查询以显示所有rate id, origin port name, destination port name, rate_min and rate_max的{​​{1}}。将源端口名称的别名命名为ports,将目标端口名称的别名命名为'source_port'

有人可以帮我解决上述情况吗?

1 个答案:

答案 0 :(得分:0)

您想要的是速率和端口表之间的简单连接->一次获取origin_name,一次获取destination_name。假设origin_id和destination_id是端口表的外键。

create table port(id int, country varchar(50), name varchar(50));
create table rate(id int, description varchar(50), rate_min int, rate_max int, Origin_id int, Destination_id int);


select a.rate id
      ,b.id as origin port name
      ,c.id as destination port name
      ,a.rate_min
      ,a.rate_max 
  from rate a
  join port b 
    on a.origin_id=b.id
  join port c
    on a.destination_id=c.id