IF()
当输入在MySQL中为null时,使用函数为date_format返回null。语法如下-
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 -> );
现在,您可以使用insert命令在表中插入一些记录。查询如下-
mysql> insert into returnNullWhenInputIsNullDemo(ShippingDate) values('2019-01-21'); mysql> insert into returnNullWhenInputIsNullDemo(ShippingDate) values(NULL); mysql> insert into returnNullWhenInputIsNullDemo(ShippingDate) values('2018-03-25'); mysql> insert into returnNullWhenInputIsNullDemo(ShippingDate) values(NULL); mysql> insert into returnNullWhenInputIsNullDemo(ShippingDate) values(NULL); mysql> insert into returnNullWhenInputIsNullDemo(ShippingDate) values('2012-04-23'); mysql> insert into returnNullWhenInputIsNullDemo(ShippingDate) values('2018-12-01'); mysql> insert into returnNullWhenInputIsNullDemo(ShippingDate) values('2016-11-13');
使用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中输入为null时为date_format返回null的查询-
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)