2018-05-10

NOT NULL列用IS NULL也能查到数据?

技术小能手 2018-05-07 09:17:13 浏览200 评论0

云栖社区


测试


odbc

摘要: 测试表DDL CREATE TABLE `t1` ( `id` int(11) DEFAULT NULL, `dt` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' ) ENGINE=InnoDB; 插入测试数据: yejr@imysql.

测试表DDL

CREATE TABLE `t1`(`id`int(11)DEFAULTNULL,`dt` datetime NOTNULLDEFAULT'0000-00-00 00:00:00')ENGINE=InnoDB;

插入测试数据:

[email protected]>insert intot1(id)select1;---不指定dt列的值[email protected]>insert into t1 select2,now();---指定dt列的值为now()[email protected]>insert intot1(id)select3;---不指定dt列的值

查询数据:

[email protected]>select*from t1 where dt is null;+------+---------------------+|id|dt|+------+---------------------+|1|0000-00-0000:00:00||3|0000-00-0000:00:00|+------+---------------------+2rows in set(0.00sec)

有没有觉得很奇怪,为什么查到了2条 dt 列值为 '0000-00-00 00:00:00' 的记录?

先查看执行计划:

[email protected]>desc select*from t1 where dt is null\G***************************1.row***************************id:1select_type:SIMPLE table:t2 partitions:NULLtype:ALLpossible_keys:NULLkey:NULLkey_len:NULLref:NULLrows:5filtered:20.00Extra:Using where1row in set,1warning(0.00sec)[email protected]>show warnings\G***************************1.row***************************Level:Note Code:1003Message:/* select#1 */select `yejr`.`t1`.`id` AS `id`,`yejr`.`t2`.`dt` AS `dt` from `yejr`.`t1` where(`yejr`.`t1`.`dt`='0000-00-00 00:00:00')

发现 IS NULL 条件被转换了,所以才能查到结果,这是为什么呢? 我尝试了调整SQL_MODE,发现并没什么卵用,最后还是在官方文档找到了答案:

For DATE and DATETIME columns that are declared as NOT NULL, you can find the special date '0000-00-00' by using a statement like this:

SELECT*FROM tbl_name WHERE date_column ISNULL

This is needed to get some ODBC applications to work because ODBC does not support a '0000-00-00' date value.

See Obtaining Auto-Increment Values, and the description for the FLAG_AUTO_IS_NULL option at Connector/ODBC Connection Parameters.

原文发布时间为:2018-05-5

本文作者:叶师傅春茶开售啦

本文来自云栖社区合作伙伴“老叶茶馆”,了解相关信息可以关注“老叶茶馆”。

你可能感兴趣的:(2018-05-10)