栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

为什么MYSQL IN关键字不考虑NULL值

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

为什么MYSQL IN关键字不考虑NULL值

这个 :

Error not in ('Timeout','Connection Error');

在语义上等效于:

Error <> 'TimeOut' AND Error <> 'Connection Error'

有关空比较的规则也适用于IN。因此,如果Error的值为NULL,则数据库无法使表达式为true。

要解决此问题,您可以这样做:

COALESCE(Error,'') not in ('Timeout','Connection Error');

或者更好:

Error IS NULL OR Error not in ('Timeout','Connection Error');

甚至更好:

 CASE WHEN Error IS NULL THEN 1 ELSE Error not in ('Timeout','Connection Error') THEN 1 END = 1

OR
不短路,CASE可以使您的查询短路


也许一个具体的例子可以说明为什么

NULL NOT IN expression
什么都不返回:

给定此数据:http :
//www.sqlfiddle.com/#!2/0d5da/11

create table tbl(  msg varchar(100) null,  description varchar(100) not null  );insert into tbl values('hi', 'greet'),(null, 'nothing');

然后执行以下表达式:

select 'hulk' as x, msg, description from tbl where msg not in ('bruce','banner');

那只会输出“ hi”。

NOT IN转换为:

select 'hulk' as x, msg, description from tbl where msg <> 'bruce' and msg <> 'banner';

NULL <> 'bruce'
无法确定,甚至不成立,甚至不成立

NULL <> 'banner'
无法确定,甚至不成立,甚至不成立

因此,空值表达式可以有效地解析为:

can't be determined AND can't bedetermined

实际上,如果您的RDBMS在SELECt上支持布尔值(例如MySQL,Postgresql),则可以看到原因:http
://www.sqlfiddle.com/#!2/d41d8/828

select null <> 'Bruce'

返回null。

这也返回null:

select null <> 'Bruce' and null <> 'Banner'

鉴于您正在使用

NOT IN
,它基本上是一个AND表达式。

NULL AND NULL

结果为NULL。因此,就像您正在执行以下操作:http :
//www.sqlfiddle.com/#!2/0d5da/12

select * from tbl where null

一无所有



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/408322.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号