使用YEAR()
和MONTH()
分别显示特定月份和年份的记录。让我们首先创建一个表-
mysql> create table DemoTable ( CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY, CustomerName varchar(20), CustomerTotalBill int, PurchasingDate date );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('John',2000,'2019-01-21'); mysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('Chris',1000,'2019-01-31'); mysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('Robert',4500,'2018-01-01'); mysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('Sam',5500,'2017-02-12'); mysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('Carol',500,'2016-01-12');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+------------+--------------+-------------------+----------------+ | CustomerId | CustomerName | CustomerTotalBill | PurchasingDate | +------------+--------------+-------------------+----------------+ | 1 | John | 2000 | 2019-01-21 | | 2 | Chris | 1000 | 2019-01-31 | | 3 | Robert | 4500 | 2018-01-01 | | 4 | Sam | 5500 | 2017-02-12 | | 5 | Carol | 500 | 2016-01-12 | +------------+--------------+-------------------+----------------+ 5 rows in set (0.00 sec)
以下是查询以显示MySQL中特定月份和年份的记录-
mysql> select *from DemoTable WHERE YEAR(DATE(PurchasingDate))=2019 AND MONTH(DATE(PurchasingDate)) = 01;
这将产生以下输出-
+------------+--------------+-------------------+----------------+ | CustomerId | CustomerName | CustomerTotalBill | PurchasingDate | +------------+--------------+-------------------+----------------+ | 1 | John | 2000 | 2019-01-21 | | 2 | Chris | 1000 | 2019-01-31 | +------------+--------------+-------------------+----------------+ 2 rows in set (0.03 sec)