加入表格时遇到问题

时间:2013-08-06 02:24:18

标签: sql sql-server join

我正在尝试编写一个查询,以显示每位乘客的名字。 这是我到目前为止所做的 - 它没有错误,也没有结果:

-- Write a query to display the Name of each passenger as well as the fare for their trip.
select passenger.name, departure_info.fare * passenger.quantity AS passenger_fare
from passenger, seat_passenger, manages, departure_info, seat_info
where departure_info.Dept_id=manages.Dept_id 
AND manages.Seat_id=seat_info.Seat_id 
AND seat_info.Seat_id=seat_passenger.Seat_id 
AND seat_passenger.Pass_id=passenger.pass_id

以下是表http://i.imgur.com/R4EFthY.png

的关系视图

1 个答案:

答案 0 :(得分:1)

使用正确的连接语法将从您的查询中进行此查询

select
    p.name, di.fare * p.quantity as passenger_fare
from passenger as p
   inner join seat_passenger as sp on sp.pass_id = p.pass_id
   inner join seat_info as si on si.seat_id = sp.seat_id
   inner join manages as m on m.seat_id = si.seat_id
   inner join departure_info as di on di.dept_it = m.dept_id

我建议您将inner joins转换为left outer joins并查看您遗失的内容

select
    p.name, di.fare * p.quantity as passenger_fare,
    sp.pass_id, si.seat_id, m.seat_id, di.dept_id
from passenger as p
   left outer join seat_passenger as sp on sp.pass_id = p.pass_id
   left outer join seat_info as si on si.seat_id = sp.seat_id
   left outer join manages as m on m.seat_id = si.seat_id
   left outer join departure_info as di on di.dept_it = m.dept_id

实际上,你甚至可以删除未使用的连接(如果你没有错过seat_info中的一些记录):

select
    p.name, di.fare * p.quantity as passenger_fare
from passenger as p
   inner join seat_passenger as sp on sp.pass_id = p.pass_id
   inner join manages as m on m.seat_id = sp.seat_id
   inner join departure_info as di on di.dept_it = m.dept_id