在 MySQL 中仅根据月份和年份进行选择?

mysqlmysqli database

要根据月份和年份选择 MySQL,请使用内置函数 YEAR() 和 MONTH()。语法如下 −

select *from yourTableName where YEAR(yourColumnName) = YearValue AND MONTH(yourColumnName) = monthValue;

为了理解上述语法,让我们创建一个表。创建表的查询如下 −

mysql> create table selectDataOnYearandMonthDemo
   −> (
   −> BookId int,
   −> BookName varchar(100), 
   −> BookDueDate datetime
   −> );
Query OK, 0 rows affected (0.57 sec)

现在您可以在表中插入一些记录。查询如下 −

mysql> insert into selectDataOnYearandMonthDemo values(101,'C in Depth',date_add(now(),interval -1 year));
Query OK, 1 row affected (0.50 sec)

mysql> insert into selectDataOnYearandMonthDemo values(102,'Let us C',date_add(curdate(),interval 1 year));
Query OK, 1 row affected (0.12 sec)

mysql> insert into selectDataOnYearandMonthDemo values(103,'SCJP Java','2018-12-5');
Query OK, 1 row affected (0.12 sec)

mysql> insert into selectDataOnYearandMonthDemo values(104,'Introduction to C++','2016-4-5');
Query OK, 1 row affected (0.24 sec)

显示我们上面插入的所有记录。显示所有记录的查询如下 −

mysql> select *from selectDataOnYearandMonthDemo;

以下是输出 −

+--------+--------------------+---------------------+
| BookId | BookName           | BookDueDate         |
+--------+--------------------+---------------------+
|    101 | C in Depth         | 2017-12-05 21:44:20 |
|    102 | Let us C           | 2019-12-05 00:00:00 |
|    103 | SCJP Java          | 2018-12-05 00:00:00 |
|    104 | Introduction to C++| 2016-04-05 00:00:00 |
+--------+--------------------+---------------------+
4 rows in set (0.00 sec)

以下是选择年份和月份的查询。查询如下 −

mysql> select *from selectDataOnYearandMonthDemo where YEAR(BookDueDate) = 2019 AND MONTH(BookDueDate) = 12;

以下是输出 −

+--------+----------+---------------------+
| BookId | BookName | BookDueDate         |
+--------+----------+---------------------+
| 102    | Let us C | 2019-12-05 00:00:00 |
+--------+----------+---------------------+
1 row in set (0.05 sec)

相关文章