Computer >> Máy Tính >  >> Lập trình >> MySQL

Truy vấn MySQL để chọn bản ghi từ một bảng trên cơ sở một số tháng cụ thể?

Bạn có thể chọn tháng cụ thể với sự trợ giúp của hàm MONTH (). Cú pháp như sau -

SELECT yourColumnName FROM yourTableName WHERE MONTH(yourColumnName) = yourValue;

Để hiểu cú pháp trên, chúng ta hãy tạo một bảng. Truy vấn để tạo bảng như sau -

mysql> create table UserLoginTimeInformation
   -> (
   -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> UserLoginDatetime datetime
   -> );
Query OK, 0 rows affected (0.55 sec)

Chèn một số bản ghi trong bảng bằng lệnh chèn. Truy vấn như sau -

mysql> insert into UserLoginTimeInformation(UserLoginDatetime) values(date_add(now(), interval 3 month));
Query OK, 1 row affected (0.14 sec)
mysql> insert into UserLoginTimeInformation(UserLoginDatetime) values('2013-05-13 13:45:34');
Query OK, 1 row affected (0.17 sec)
mysql> insert into UserLoginTimeInformation(UserLoginDatetime) values('2013-06-11 12:41:04');
Query OK, 1 row affected (0.19 sec)
mysql> insert into UserLoginTimeInformation(UserLoginDatetime) values('2012-05-25 15:03:24');
Query OK, 1 row affected (0.23 sec)
mysql> insert into UserLoginTimeInformation(UserLoginDatetime) values('2017-05-21 12:12:40');
Query OK, 1 row affected (0.10 sec)
mysql> insert into UserLoginTimeInformation(UserLoginDatetime) values('2018-09-29 11:30:34');
Query OK, 1 row affected (0.10 sec)
mysql> insert into UserLoginTimeInformation(UserLoginDatetime) values('2016-03-10 16:40:45');
Query OK, 1 row affected (0.27 sec)

Hiển thị tất cả các bản ghi từ bảng bằng cách sử dụng một câu lệnh chọn. Truy vấn như sau -

mysql> select *from UserLoginTimeInformation;

Sau đây là kết quả -

+--------+---------------------+
| UserId | UserLoginDatetime   |
+--------+---------------------+
| 1 | 2019-05-13 15:01:24 |
| 2 | 2013-05-13 13:45:34 |
| 3 | 2013-06-11 12:41:04 |
| 4 | 2012-05-25 15:03:24 |
| 5 | 2017-05-21 12:12:40 |
| 6 | 2018-09-29 11:30:34 |
| 7 | 2016-03-10 16:40:45 |
+--------+---------------------+
7 rows in set (0.00 sec)

Ví dụ

Đây là truy vấn để chọn tất cả các bản ghi từ bảng trên cơ sở số tháng -

mysql> select UserLoginDatetime from UserLoginTimeInformation where MONTH(UserLoginDatetime) = 5;

Đầu ra

+---------------------+
| UserLoginDatetime |
+---------------------+
| 2019-05-13 15:01:24 |
| 2013-05-13 13:45:34 |
| 2012-05-25 15:03:24 |
| 2017-05-21 12:12:40 |
+---------------------+
4 rows in set (0.00 sec)