有没有办法在 MySQL 中从日期中减去天数?
是的,你可以使用 date_sub() 从日期中减去天数。以下是语法 −
select date_sub(yourColumnName,Interval yourAmountOfDays day) from yourTableName;
我们首先创建一个表 −
mysql> create table DemoTable660(AdmissionDate datetime); Query OK, 0 rows affected (0.82 sec)
使用插入命令在表中插入一些记录 −
mysql> insert into DemoTable660 values('2018-01-24'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable660 values('2019-07-10'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable660 values('2020-11-20'); Query OK, 1 row affected (0.59 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable660;
这将产生以下输出 −
+---------------------+ | AdmissionDate | +---------------------+ | 2018-01-24 00:00:00 | | 2019-07-10 00:00:00 | | 2020-11-20 00:00:00 | +---------------------+ 3 rows in set (0.00 sec)
以下是 MySQL 中从日期中减去天数的查询 −
mysql> select date_sub(AdmissionDate,Interval 5 day) from DemoTable660;
这将产生以下输出 −
+----------------------------------------+ | date_sub(AdmissionDate,Interval 5 day) | +----------------------------------------+ | 2018-01-19 00:00:00 | | 2019-07-05 00:00:00 | | 2020-11-15 00:00:00 | +----------------------------------------+ 3 rows in set (0.00 sec)
广告