如何在 MySQL 表中获取特定月份和年份的记录?
mysqlmysqli database
使用 YEAR() 和 MONTH() 分别显示特定月份和年份的记录。让我们首先创建一个表 −
mysql> create table DemoTable ( CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY, CustomerName varchar(20), CustomerTotalBill int, PurchasingDate date ); Query OK, 0 rows affected (0.83 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('John',2000,'2019-01-21'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('Chris',1000,'2019-01-31'); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('Robert',4500,'2018-01-01'); Query OK, 1 row affected (0.24 sec) mysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('Sam',5500,'2017-02-12'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('Carol',500,'2016-01-12'); Query OK, 1 row affected (0.17 sec)
使用 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)