Reputation: 107
I have been struggling and would really appreciate some assistance:
I have two tables flights and carriers.
flights
Flight_ID | Airport_Origin | Airport_Destination | Carrier_ID
1 | DOM | IAD | 1
2 | IAD | DOM | 4
3 | BAL | UEI | 1
4 | LAX | CHI | 2
5 | VAS | SDA | 3
6 | MUM | PAR | 2
7 | LAD | BOS | 4
carriers
carrier_ID | Carrier_Name
1 | American
2 | southwest
3 | delta
4 | united
5 | spirit
I would like to display each airline carrier by its name with a count of number of flights. And if the airline has no flights, it should show 0 and should display all carriers.
Output should be:
CarrierName | NumberofFlights
American | 2
southwest | 2
delta | 1
united | 2
spirit | 0
my code:
select carriers.Carrier_Name AS 'Carrier Name', count(*) AS 'Number of Flights'
from flights
inner join carriers
on flights.Carrier_ID = carriers.Carrier_ID
group by Carrier_Name
Order BY Carrier_Name
;
I cannot seem to show the carrier with no flights as 0. My output is as follows:
Upvotes: 1
Views: 75
Reputation: 9318
That is a LEFT JOIN
(outer join) when records from right part of join may not exist:
select
c.Carrier_Name AS 'Carrier Name', count(f.Flight_ID) AS 'Number of Flights'
from carriers c
left join flights f on f.Carrier_ID = c.Carrier_ID
group by Carrier_Name
order by Carrier_Name
also this can be accomplished by such a subquery:
select
c.Carrier_Name AS 'Carrier Name',
(select count(*) from flights f where f.Carrier_ID = c.Carrier_ID) AS 'Number of Flights'
from carriers c
order by Carrier_Name
INNER JOIN
means that corresponding records from both parts of join must exist.
Upvotes: 0
Reputation: 781741
You need to use an outer join so the result will include rows with no match. And then the COUNT
function has to count a row in the flights
table so it won't count the null row that results when there's no match.
SELECT c.carrier_name AS `Carrier Name`, COUNT(f.Flight_ID) AS `Number of Flights`
FROM carriers AS c
LEFT JOIN flights AS f ON f.carrier_ID = c.carrier_ID
GROUP BY c.carrier_name
ORDER BY c.carrier_name
Upvotes: 1