我有以下查询:
SELECT airportname, COUNT(DISTINCT foundBag.id) countFound, COUNT(DISTINCT lostBag.id) countLost
FROM airports
INNER JOIN foundBag ON airport_id = foundBag.airportDest
INNER JOIN lostBag ON airport_id = lostBag.airportDest
GROUP BY airport.airportname");
我现在所拥有的:有3列的表格:机场名称,找到的行李数和丢失的行李数。
当两个列都填充时,它仅显示一个机场(行)。
我想要两件事:
即使在没有丢失/找不到行李的情况下也能显示所有机场。
显示丢失/找到行李的机场(因此当填满1或两列时)
我用When等尝试过此方法,但它一直给我错误。我也尝试过EXISTS,但是我是SQL的新手,所以我不知道它是如何工作的...
有人有解决方案吗?
亲切的问候,
LTKort
最佳答案
这对于两种情况都应该起作用:
SELECT airportname, COUNT(DISTINCT foundBag.id) countFound, COUNT(DISTINCT lostBag.id) countLost
FROM airports
LEFT JOIN foundBag ON airport_id = foundBag.airportDest
LEFT JOIN lostBag ON airport_id = lostBag.airportDest
WHERE foundBag.airportDest is not null
or lostBag.airportDest is not null
GROUP BY airport.airportname