当没有数据存在时,查询返回1行

时间:2012-05-24 14:52:32

标签: mysql null

我正在运行同一查询的多个实例。下面的版本不应该返回任何数据,但我在每一列中得到1行'null':

SELECT (CASE ScanName WHEN 'SYSTEM-HQ' THEN 'HQ
System' END) AS System, 
sum(CASE pspplMSSeverity WHEN 1 THEN 10 WHEN 2 THEN 9 WHEN 
3 THEN 6 WHEN 4 THEN 3 END) AS Score, 
(sum(CASE pspplMSSeverity WHEN 1 THEN 10 WHEN 2 THEN 9 
WHEN 3 THEN 6 WHEN 4 THEN 3 END)/COUNT(pspplMSSeverity)) AS 
Grade 
FROM missingpatches 
WHERE ScanName like '%SYSTEM-HQ%' 
ORDER BY LAST_UPDATE DESC LIMIT 1 

如何修改此查询以确保我只在有效值存在时返回数据?

这可能是由于在主SQL语句中使用了导致返回Null数据的Case和Sum吗?

2 个答案:

答案 0 :(得分:1)

SELECT (CASE ScanName WHEN 'SYSTEM-HQ' THEN 'HQ
System' END) AS System, 
sum(CASE pspplMSSeverity WHEN 1 THEN 10 WHEN 2 THEN 9 WHEN 
3 THEN 6 WHEN 4 THEN 3 END) AS Score, 
(sum(CASE pspplMSSeverity WHEN 1 THEN 10 WHEN 2 THEN 9 
WHEN 3 THEN 6 WHEN 4 THEN 3 END)/COUNT(pspplMSSeverity)) AS 
Grade 
FROM missingpatches 
WHERE ScanName like '%SYSTEM-HQ%' 
HAVING System IS NOT NULL # Added
ORDER BY LAST_UPDATE DESC LIMIT 1 

尝试添加HAVING。

答案 1 :(得分:0)

missingpatches最有可能包含1行满足

WHERE ScanName like '%SYSTEM-HQ%' 

即。 ScanName包含'SYSTEM-HQ'但不完全等于'SYSTEM-HQ'的行,你在select的1st col中等同于'SYSTEM-HQ'。

在SQL中,在连接表和评估子句之后计算列。因此,您看到的行实际上符合where子句标准。