最近在测试数据,偶尔需要写sql进行数据比对,例如这样的语句:
if( column_a != column_b, 1, 0),万万没想到就是这样的sql语句差点要了我的命。
其实对一般的数据,这条校验语句是没有问题的,最后再筛选一下=1的值,就可以把不一样的数据给筛出来了,但是,但是,但是,在遇到null值的时候出现问题了,在我的常识的理解中,或者在我对其他编程语言的理解中,if(null != “xxxx”, 1, 0) 应该是返回1的,但是sql中就是这么奇怪。
关键是有时候我们忽略了这一点,尤其是两个表join之后,字段之间的比较,你很难意识到有些字段有null,null值不能参与equal比较。
This is by design. NULL is not equal (or unequal) to anything.
You can’t use the not equal to operator to compare against NULL. Actually, this may depend on your DBMS and its configuration.
In SQL null is not equal (=) to anything—not even to another null. According to the three-valued logic of SQL, the result of null = null is not true but unknown. SQL has the is [not] null predicate to test if a particular value is null.
https://modern-sql.com/feature/is-distinct-from#:~:text=In%20SQL%20null%20is%20not%20equal%20%28%20%3D%29,that%20treats%20two%20null%20values%20as%20the%20same.
通俗来讲,就是当你使用不等于进行筛选的时候,一定要注意,因为null不会被筛选出来,这样可能和你所期望的结果大相径庭。
<=>
这个操作符好像是一种解决方法,对于非null值,其表现和=是一样的,对于null值,null <=> null返回True, 如果只有一个只为null就返回False。
Returns same result with EQUAL(=) operator for non-null operands, but returns TRUE if both are NULL, FALSE if one of the them is NULL. (As of version 0.9.0.)