使用两个表计数并显示0表示没有结果SQL

时间:2016-02-19 17:19:16

标签: mysql mysql-workbench

我一直在努力,非常感谢一些帮助:

我有两张桌子航班和航空公司。

航班

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

载体

carrier_ID | Carrier_Name
1 | American 
2 | southwest
3 | delta
4 | united
5 | spirit

我希望按照其名称显示每家航空公司的航班数量。如果航空公司没有航班,它应该显示0并且应该显示所有航空公司。

输出应为:

CarrierName | NumberofFlights
American    | 2
southwest   | 2
delta       | 1
united      | 2
spirit      | 0

我的代码:

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
;

我似乎无法向没有航班的航空公司显示为0.我的输出如下:

enter image description here

2 个答案:

答案 0 :(得分:1)

您需要使用外部联接,因此结果将包含不匹配的行。然后COUNT函数必须计算flights表中的一行,这样它就不会计算在没有匹配时产生的空行。

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

答案 1 :(得分:0)

当加入的右侧部分的记录可能不存在时,这是LEFT JOIN(外部联接):

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

这也可以通过这样的子查询来实现:

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表示来自的两个部分的相应记录必须