sql 在not in 子查询有null值情况下经常出现的陷阱

如果下:TempSalesPriceFixedValues表和SalesPriceFixedValues表,要求查询出在TempSalesPriceFixedValues表中且不在SalesPriceFixedValues表中的记录。

select distinct Ctyp from TempSalesPriceFixedValues where  Ctyp not in  (
select distinct ConditonTypeCode from SalesPriceFixedValues
)

查询结果:

我们看到没有数据,因为SalesPriceFixedValues表里有NULL值。

select distinct ConditonTypeCode from SalesPriceFixedValues

正确的写法:

select distinct Ctyp from TempSalesPriceFixedValues where  Ctyp not in  (
select distinct ConditonTypeCode from SalesPriceFixedValues where ConditonTypeCode is not null
)

原因:

NULL不能进行某些逻辑操作:

–如果null参与算术运算,则该算术表达式的值为null。(例如:+,-,*,/ 加减乘除)

–如果null参与比较运算,则结果可视为false。(例如:>=,<=,<>  大于,小于,不等于)

–如果null参与聚集运算,则聚集函数都置为null。除count(*)之外。

--如果在not in子查询中有null值的时候,则不会返回数据。

勤劳一日,便得一夜安眠;勤劳一生,便得幸福长眠。
原文地址:https://www.cnblogs.com/zhaomengmeng/p/4938864.html