忽略 MySQL 查询中的日期范围中的年份?
若要忽略日期范围中的年份,请在 between 子句中使用 DATE_FORMAT()。我们首先创建一个演示表。创建表的查询如下所示 -
mysql> create table igonreYearDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> ShippingDate date -> ); Query OK, 0 rows affected (0.75 sec)
使用 insert 命令在表中插入一些记录。查询如下所示 -
mysql> insert into igonreYearDemo(ShippingDate) values('2016-01-31'); Query OK, 1 row affected (0.16 sec) mysql> insert into igonreYearDemo(ShippingDate) values('2018-01-31'); Query OK, 1 row affected (0.13 sec) mysql> insert into igonreYearDemo(ShippingDate) values('2015-06-23'); Query OK, 1 row affected (0.17 sec) mysql> insert into igonreYearDemo(ShippingDate) values('2015-06-23'); Query OK, 1 row affected (0.15 sec) mysql> insert into igonreYearDemo(ShippingDate) values('2014-02-01'); Query OK, 1 row affected (0.20 sec) mysql> insert into igonreYearDemo(ShippingDate) values('2019-01-31'); Query OK, 1 row affected (0.16 sec) mysql> insert into igonreYearDemo(ShippingDate) values('2019-02-14'); Query OK, 1 row affected (0.11 sec) mysql> insert into igonreYearDemo(ShippingDate) values('2019-03-12'); Query OK, 1 row affected (0.19 sec)
使用 select 语句显示表中的所有记录。查询如下所示 -
mysql> select *from igonreYearDemo;
以下是输出 -
+----+--------------+ | Id | ShippingDate | +----+--------------+ | 1 | 2016-01-31 | | 2 | 2018-01-31 | | 3 | 2015-06-23 | | 4 | 2015-06-23 | | 5 | 2014-02-01 | | 6 | 2019-01-31 | | 7 | 2019-02-14 | | 8 | 2019-03-12 | +----+--------------+ 8 rows in set (0.00 sec)
以下是对指定日期范围忽略年份的查询 -
mysql> select *from igonreYearDemo tbl where DATE_FORMAT(tbl.ShippingDate, '%m-%d') between '01-01' and '03-31';
以下是输出 -
+----+--------------+ | Id | ShippingDate | +----+--------------+ | 1 | 2016-01-31 | | 2 | 2018-01-31 | | 5 | 2014-02-01 | | 6 | 2019-01-31 | | 7 | 2019-02-14 | | 8 | 2019-03-12 | +----+--------------+ 6 rows in set (0.00 sec)
广告