如何通过包含空值来编写查询

时间:2013-02-04 19:02:18

标签: mysql

我有一个查询

SELECT sum(cash)  from bought_cash WHERE uid=1 AND source NOT IN ('a', 'b')  

将结果显示为140

 SELECT sum(cash)  from bought_cash WHERE uid=1 AND source  IN ('a', 'b')  

给出NULL

SELECT sum(cash)  from bought_cash WHERE uid=1 

将结果显示为240

SELECT sum(cash)  from bought_cash WHERE uid=1 and source is null  

将结果显示为100

如何编写查询,以便第一个查询通过包含空值来将结果显示为240

2 个答案:

答案 0 :(得分:1)

您还可以尝试下一步:

select sum(cash) 
from bought_cash
where uid = 1 and (source is null or source not in ('a', 'b'))

答案 1 :(得分:0)

您可以尝试这样的事情:

select sum(cash) from bought_cash 
    where uid=1 and isnull(source, 'c') not in ('a', 'b')

这应该将空条目映射到值'c',它不是'a'或'b',因此应该包含在结果集中。