mySQL如何将NULL显示为0

时间:2018-12-11 18:30:16

标签: mysql sql join null subquery

在没有数据的情况下尝试让我的代码显示0而不是NULL:

SELECT e.EntryName AS Name, e.EntryDate AS Date,

(SELECT COALESCE(COUNT(l.crashNumber), 0)
FROM Crash l
WHERE l.crashName = e.EntryName 
AND l.crashDate = e.EntryDate
GROUP BY l.crashNumber
ORDER BY COUNT(l.crashNumber) DESC
LIMIT 1)

FROM 
(SELECT e.EntryName, e.EntryDate
FROM Entry e
GROUP BY e.EntryName, e.EntryDate)

e;

您可以看到我尝试使用COALESCE,而我尝试使用ISNULL。 这个想法是,并非所有种族都崩溃,因此它们的输出显示为NULL,尽管我希望当它为NULL时应该显示0。

1 个答案:

答案 0 :(得分:3)

使用:

SELECT e.raceEntryRaceName AS raceName, e.raceEntryRaceDate AS raceDate,

Coalesce( ( SELECT COUNT(l.pitstopRaceNumber)
           FROM PitStops l
           WHERE l.pitstopRaceName = e.raceEntryRaceName 
             AND l.pitstopRaceDate = e.raceEntryRaceDate
           GROUP BY l.pitstopRaceNumber
           ORDER BY COUNT(l.pitstopRaceNumber) DESC
           LIMIT 1), 0) AS mostPitstops

FROM .....