内部连接两个表的2列到相同的ID

时间:2017-11-19 21:21:20

标签: sql sqlite inner-join

我开始学习“sqllite3”,我遇到了一个我无法弄清楚的问题。

我有这些表

Schema

我想选择 每位乘客的下列日期: 姓名,性别,年龄,票,票价,始发港和目的港。 但在Origin和目标端口我想显示端口名称而不是数字。 我管道显示除了端口之外的所有数据,我知道我需要使用Alias,但不知道如何。 有人可以帮忙吗?

select Passengers.Passengerid as "PassengerId", Classes.Class_Name as 
"Passenger_Class", Passengers.Name, Passengers.Sex,Passengers.Age, 
Travels.Ticket,Travels.Fare, Ports.Port_ID as "Embarked",Ports.Port_ID as 
"Destination" from Passengers
inner join Travels on Passengers.Passengerid = Travels.Passengerid
inner join Travel_Options on Travels.Travel_ID = Travel_Options.Travel_ID
inner join Ports on Travel_Options.Origin_Port_ID =  Ports.Port_ID
inner join Ports on Travel_Options.Destination_ID =  Ports.Port_ID
inner join Classes on Travel_Options.Class_ID = Classes.Class_ID;

1 个答案:

答案 0 :(得分:2)

表格需要单独的别名。事实上,我建议所有表的表别名:

select p.Passengerid, c.Class_Name as Passenger_Class,
       p.Name, p.Sex, p.Age, 
       t.Ticket, t.Fare, po.port_name as Embarked, pd.port_name as  Destination
from Passengers p inner join
     Travels t
     on p.Passengerid = t.Passengerid inner join
     Travel_Options o
     on t.Travel_ID = o.Travel_ID inner join
     Ports po
     on o.Origin_Port_ID = po.Port_ID inner join
     Ports pd
     on o.Destination_ID = pd.Port_ID inner join
     Classes c
     on o.Class_ID = c.Class_ID;