我有以下查询:
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
关于mysql - 显示SQL查询的所有结果(包括where count 0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41574611/