MySQL 中输入为空时 date_format 返回空值?
mysqlmysqli database更新于 2024/10/14 22:04:17
使用 IF() 函数在 MySQL 中输入为空时 date_format 返回空值。语法如下 −
SELECT IF(yourDateColumnName,date_format(yourDateColumnName, '%d/%m/%Y'),NULL) FROM yourTableName;
为了理解上述语法,让我们创建一个表。创建表的查询如下 −
mysql> create table returnNullWhenInputIsNullDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> ShippingDate datetime -> ); Query OK, 0 rows affected (1.21 sec)
现在,您可以使用 insert 命令在表中插入一些记录。查询如下 −
mysql> insert into returnNullWhenInputIsNullDemo(ShippingDate) values('2019-01-21');
Query OK, 1 row affected (0.37 sec)
mysql> insert into returnNullWhenInputIsNullDemo(ShippingDate) values(NULL);
Query OK, 1 row affected (0.16 sec)
mysql> insert into returnNullWhenInputIsNullDemo(ShippingDate) values('2018-03-25');
Query OK, 1 row affected (0.17 sec)
mysql> insert into returnNullWhenInputIsNullDemo(ShippingDate) values(NULL);
Query OK, 1 row affected (0.17 sec)
mysql> insert into returnNullWhenInputIsNullDemo(ShippingDate) values(NULL);
Query OK, 1 row affected (0.10 sec)
mysql> insert into returnNullWhenInputIsNullDemo(ShippingDate) values('2012-04-23');
Query OK, 1 row affected (0.20 sec)
mysql> insert into returnNullWhenInputIsNullDemo(ShippingDate) values('2018-12-01');
Query OK, 1 row affected (0.23 sec)
mysql> insert into returnNullWhenInputIsNullDemo(ShippingDate) values('2016-11-13');
Query OK, 1 row affected (0.13 sec)
使用 select 语句显示表中的所有记录。查询如下 −
mysql> select *from returnNullWhenInputIsNullDemo;
以下是输出 −
+----+---------------------+ | Id | ShippingDate | +----+---------------------+ | 1 | 2019-01-21 00:00:00 | | 2 | NULL | | 3 | 2018-03-25 00:00:00 | | 4 | NULL | | 5 | NULL | | 6 | 2012-04-23 00:00:00 | | 7 | 2018-12-01 00:00:00 | | 8 | 2016-11-13 00:00:00 | +----+---------------------+ 8 rows in set (0.00 sec)
当 MySQL 中输入为空时,以下查询将返回 date_format 为空 −
mysql> SELECT IF(ShippingDate,date_format(ShippingDate, '%d/%m/%Y'),NULL) FROM returnNullWhenInputIsNullDemo;
以下是输出 −
+-------------------------------------------------------------+ | IF(ShippingDate,date_format(ShippingDate, '%d/%m/%Y'),NULL) | +-------------------------------------------------------------+ | 21/01/2019 | | NULL | | 25/03/2018 | | NULL | | NULL | | 23/04/2012 | | 01/12/2018 | | 13/11/2016 | +-------------------------------------------------------------+ 8 rows in set (0.05 sec)
相关文章
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

