要基于月和年选择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 −> );
现在,您可以在表中插入一些记录。查询如下-
mysql> insert into selectDataOnYearandMonthDemo values(101,'C in Depth',date_add(now(),interval -1 year)); mysql> insert into selectDataOnYearandMonthDemo values(102,'Let us C',date_add(curdate(),interval 1 year)); mysql> insert into selectDataOnYearandMonthDemo values(103,'SCJP Java','2018-12-5'); mysql> insert into selectDataOnYearandMonthDemo values(104,'Introduction to C++','2016-4-5');
显示我们在上方插入的所有记录。显示所有记录的查询如下-
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)