Sql如果一列返回null,则整个结果集为null

时间:2014-12-11 09:57:36

标签: mysql sql

我有一个问题:

select 'False' as COL_1, coalesce(sum(volume),0) as COL_2 
from table1
where eligible like 'False%' and Month = :month

基本上我正在创建第一列来读取False以及找到了什么结果,我的问题是如果我的col_2返回null,那么它仍会在结果中显示col_1 false。

我想要它,以便如果col_2返回null,整个查询返回null,我一直在玩coalesce,notnull,ifnull等......无济于事。

感谢任何帮助!

3 个答案:

答案 0 :(得分:1)

SELECT IF(SUM(volume) = 0, NULL, 'False') AS COL_1, SUM(volume) AS COL_2 ...

答案 1 :(得分:0)

SELECT CASE WHEN (coalesce(sum(volume),0)) IS NULL
            THEN NULL
            ELSE 'False' 
       END AS COL_1, 
       coalesce(sum(volume),0) AS COL_2 
FROM table1 
WHERE eligible LIKE 'False%' AND Month = :month

答案 2 :(得分:0)

select 'False' as COL_1, sum(volume) as COL_2 
from table1 where eligible like 'False%' and Month = :month  
having sum(volume) is not null

sum是一个聚合函数。如果要在聚合结果上添加where条件,则必须在select的having子句部分中定义它。

当我们过滤sum(volume)= null的情况时,不再需要合并。