在 MySQL 中添加 DATE 和 TIME 字段以获取 DATETIME 字段?
mysqlmysqli database
您可以使用 CONCAT() 函数设置日期和时间字段以获取 DATETIME 字段。
让我们创建一个演示表
mysql> create table getDateTimeFieldsDemo -> ( -> ShippingDate date, -> ShippingTime time, -> Shippingdatetime datetime -> ); Query OK, 0 rows affected (0.50 sec)
使用 insert 命令在表中插入一些记录。 查询语句如下 −
mysql> insert into getDateTimeFieldsDemo(ShippingDate,ShippingTime) values('2018-01-21','09:45:34'); Query OK, 1 row affected (0.16 sec) mysql> insert into getDateTimeFieldsDemo(ShippingDate,ShippingTime) values('2013-07-26','13:21:20'); Query OK, 1 row affected (0.13 sec) mysql> insert into getDateTimeFieldsDemo(ShippingDate,ShippingTime) values('2017-12-31','15:31:40'); Query OK, 1 row affected (0.17 sec) mysql> insert into getDateTimeFieldsDemo(ShippingDate,ShippingTime) values('2019-03-07','12:13:34'); Query OK, 1 row affected (0.41 sec)
使用 select 语句显示表中的所有记录。查询如下 −
mysql> select *from getDateTimeFieldsDemo;
下面是输出结果
+--------------+--------------+------------------+ | ShippingDate | ShippingTime | Shippingdatetime | +--------------+--------------+------------------+ | 2018-01-21 | 09:45:34 | NULL | | 2013-07-26 | 13:21:20 | NULL | | 2017-12-31 | 15:31:40 | NULL | | 2019-03-07 | 12:13:34 | NULL | +--------------+--------------+------------------+ 4 rows in set (0.00 sec)
这是在 MySQL 中添加 DATE 和 TIME 字段以获取 DATETIME 字段的查询
mysql> update getDateTimeFieldsDemo set Shippingdatetime=concat(ShippingDate," ",ShippingTime); Query OK, 4 rows affected (0.09 sec) Rows matched: 4 Changed: 4 Warnings: 0
现在再次检查表记录。查询语句如下 −
mysql> select *from getDateTimeFieldsDemo;
下面是输出结果
+--------------+--------------+---------------------+ | ShippingDate | ShippingTime | Shippingdatetime | +--------------+--------------+---------------------+ | 2018-01-21 | 09:45:34 | 2018-01-21 09:45:34 | | 2013-07-26 | 13:21:20 | 2013-07-26 13:21:20 | | 2017-12-31 | 15:31:40 | 2017-12-31 15:31:40 | | 2019-03-07 | 12:13:34 | 2019-03-07 12:13:34 | +--------------+--------------+---------------------+ 4 rows in set (0.00 sec)