嵌套查询显示2个表中的2列

时间:2012-10-20 09:14:18

标签: mysql

客户

custno  |Custname
1       |Melinda
2       |Micheal
4       |Andrew

飞行

FlightNo | Day      | Destination | Cost
AF394    |monday    |Cape Town    |2700
FL2X     |Tuesday   |Paris        |5000
HK101    |Sunday    |hong kong    |3500

预订 Custno | Flightno |费用

1       | AF394    |2700
1       |FL2X      |5000
1       |HK101     |3500
2       |HK101     |3500
6       |AF394     |2700
7       |AF394     |2700

问题 对于名为Melinda的客户,显示预订详细信息由CUSTNO,FKIGHTNO,DESTINATINDAY组成。

我是MySQL的初学者,希望有人能帮我解决问题!!

3 个答案:

答案 0 :(得分:0)

--with joins
select r1.custno,r1.flightno,f1.destination,f1.day
from customer c1 join reservation r1 on c1.custno = r1.custno
                 join flight f1 on r1.flightno = f1.flightno
where c1.custname = 'Melinda'

--with nested queries
select (select custno from customer where custname = 'Melinda') custno,
        f1.flightno,f1.destination,f1.day
from flight f1 
where exists (
               select 1 
               from reservation 
               where flightno = f1.flightno and 
                     custno = (
                                select custno
                                from customer 
                                where custname = 'Melinda'
                               )
              )

答案 1 :(得分:0)

SELECT Customer.custno, Reservation.Flightno, Flight.Destination, Flight.Day
FROM Flight LEFT OUTER JOIN Reservation ON Flight.FlightNo = Reservation.Flightno RIGHT OUTER JOIN Customer ON Reservation.Custno = Customer.custno WHERE (Customer.Custname = 'Melinda')

结果集

1   AF394   Cape Town   monday
1   FL2X    Paris           Tuesday
1   HK101   hong kong   Sunday

答案 2 :(得分:0)

select
(select custno from customer where custname='Melinda'), 
custno, 
flightno, 
day, 
destination 

from flight 
where flightno in (select flightno 
                   from reservation 
                   where custno in (select from where custname='Melinda'))