sql中的!=操作符的天坑(务必警觉)(=在处理null时也是同样有坑)

最近在测试数据,偶尔需要写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.)

在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值