比较MySQL中日期字段的月份和日份?
使用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
-> );
Query OK, 0 rows affected (0.49 sec)
用插入命令在表中插入一些记录。
查询如下
mysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2014-01-31');
Query OK, 1 row affected (0.20 sec)
mysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2014-10-11');
Query OK, 1 row affected (0.16 sec)
mysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2016-09-12');
Query OK, 1 row affected (0.08 sec)
mysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2017-04-25');
Query OK, 1 row affected (0.08 sec)
mysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2018-12-25');
Query OK, 1 row affected (0.08 sec)
mysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2019-02-27');
Query OK, 1 row affected (0.07 sec)
使用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)
阅读更多:MySQL 教程