您可以借助DATE_FORMAT()在MySQL中仅将日期和月份与日期字段进行比较。
语法如下
select *from yourTableName WHERE DATE_FORMAT(yourColumnName, '%m-%d') = DATE_FORMAT('yourValue', '%m-%d') and yourCondition;
为了理解上述语法,让我们创建一个表。创建表的查询如下
mysql> create table compareDayAndMonthDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> compareDayAndTime date -> );
使用insert命令在表中插入一些记录。
查询如下
mysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2014-01-31'); mysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2014-10-11'); mysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2016-09-12'); mysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2017-04-25'); mysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2018-12-25'); mysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2019-02-27');
使用select语句显示表中的所有记录。
查询如下
mysql> select *from compareDayAndMonthDemo;
以下是输出
+----+-------------------+ | Id | compareDayAndTime | +----+-------------------+ | 1 | 2014-01-31 | | 2 | 2014-10-11 | | 3 | 2016-09-12 | | 4 | 2017-04-25 | | 5 | 2018-12-25 | | 6 | 2019-02-27 | +----+-------------------+ 6 rows in set (0.00 sec)
这是只比较日期和月份的查询
mysql> select *from compareDayAndMonthDemo -> WHERE DATE_FORMAT(compareDayAndTime, '%m-%d') = DATE_FORMAT('2019-01-31', '%m-%d') and Id=1;
以下是输出
+----+-------------------+ | Id | compareDayAndTime | +----+-------------------+ | 1 | 2014-01-31 | +----+-------------------+ 1 row in set (0.00 sec)
如果只需要日期和月份,请使用以下查询
mysql> select DATE_FORMAT(compareDayAndTime, '%m-%d') AS DayAndMonthOnly from compareDayAndMonthDemo -> WHERE DATE_FORMAT(compareDayAndTime, '%m-%d') = DATE_FORMAT('2019-01-31', '%m-%d') and Id=1;
以下是输出
+-----------------+ | DayAndMonthOnly | +-----------------+ | 01-31 | +-----------------+ 1 row in set (0.00 sec)