理解SQL中not in 与null值的真实含义

A not in B的原理是拿A表值与B表值做是否不等的比较, 也就是a != b. 在sql中, null是缺失未知值而不是空值。

当你判断任意值a != null时, 官方说, "You cannot use arithmetic comparison operators such as =, <, or <> to test for NULL", 任何与null值的对比都将返回null. 因此返回结果为否,这点可以用代码 select if(1 = null, 'true', 'false')证实.

举个例子

sql 复制代码
select id,case when p_id is null then 'Root' 
when id not in (select p_id from tree) then 'Leaf' end type
else 'Inner' 
from tree

这种写法会导致Leaf结果完全看不到

从上述原理可见, 当询问 id not in (select p_id from tree)时, 因为p_id有null值, 返回结果全为false, 于是跳到else的结果, 返回值为inner. 所以在答案中,leaf结果从未彰显,全被inner取代.

相关推荐
ALLSectorSorft40 分钟前
相亲小程序个人资料管理系统模块搭建
服务器·网络·数据库·python·sql
tuokuac3 小时前
SQL中的LEFT JOIN
数据库·sql
tuokuac3 小时前
SQL中的GROUP BY用法
数据库·sql
百川17 小时前
sqli-labs靶场Less24
sql·web安全
wuxuanok19 小时前
SQL理解——INNER JOIN
数据库·sql
天翼云开发者社区19 小时前
sql优化谓词下推在join场景中的应用
sql·关系数据库
染落林间色21 小时前
达梦数据库权限体系详解:系统权限与对象权限
数据库·后端·sql
Lx3521 天前
子查询扁平化技巧:减少嵌套层级的查询重构
sql·mysql
Catfood_Eason1 天前
MyBatis与Spring的整合
sql·spring·mybatis
青年夏日科技工作者1 天前
从 MySQL 迁移到 TiDB:使用 SQL-Replay 工具进行真实线上流量回放测试 SOP
sql·mysql·tidb