Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

การ SELECT ข้อมูลตามเดือนใน MySQL

ใช้ฟังก์ชัน MONTH() เพื่อกรองข้อมูลตามเดือน

สร้างตารางและเพิ่มข้อมูล

mysql> create table DemoTable1599 ( Shippingdate datetime ); 
Query OK, 0 rows affected (0.78 sec)
mysql> insert into DemoTable1599 values('2019-10-21'); 
Query OK, 1 row affected (0.28 sec) 
mysql> insert into DemoTable1599 values('2018-12-12'); 
Query OK, 1 row affected (0.35 sec) 
mysql> insert into DemoTable1599 values('2015-11-21'); 
Query OK, 1 row affected (0.34 sec) 
mysql> insert into DemoTable1599 values('2017-12-31'); 
Query OK, 1 row affected (0.20 sec) 
mysql> insert into DemoTable1599 values('2018-12-26'); 
Query OK, 1 row affected (0.17 sec)

คิวรี่เลือกเฉพาะเดือน ธันวาคม (12)

mysql> select * from DemoTable1599 where month(Shippingdate)=12;

ผลลัพธ์

+---------------------+ 
| Shippingdate        | 
+---------------------+ 
| 2018-12-12 00:00:00 | 
| 2017-12-31 00:00:00 | 
| 2018-12-26 00:00:00 | 
+---------------------+ 
3 rows in set (0.00 sec)

สามารถใช้ YEAR() ร่วมกับได้ หากต้องการกรองปีและเดือนพร้อมกัน เช่น where year(date)=2018 and month(date)=12