2012-10-20 55 views
2

嵌套查詢顯示器2分從2個表

顧客

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 

問題 顯示預約內容包括CUSTNO,FKIGHTNO,DESTINATINDAY名爲梅琳達客戶。

我是m初學者MySQL,希望有人能幫我解決問題!!

回答

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' 
           ) 
      ) 
+0

哇!謝謝!!! 真的是天賦! –

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 
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'))