篩選 MySQL 中當天、當月和當年的記錄?
假設你有一個包含 UserLoginTime 列的表,其中儲存了一些示例值。這是使用者的登入時間,我們需要根據當天、當月和當年,即當前日期,篩選所有這些記錄。我們將
現在,讓我們建立上面討論的表
mysql> create table userLoginInformation - > ( - > UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, - > UserName varchar(20), - > UserLoginTime datetime - > ); Query OK, 0 rows affected (0.79 sec)
使用 insert 命令在表中插入一些記錄。
查詢如下
mysql> insert into userLoginInformation(UserName,UserLoginTime) values('John','2016-02-12');
Query OK, 1 row affected (0.18 sec)
mysql> insert into userLoginInformation(UserName,UserLoginTime) values('Carol','2019-01-31');
Query OK, 1 row affected (0.16 sec)
mysql> insert into userLoginInformation(UserName,UserLoginTime) values('Bob','2019-02-19');
Query OK, 1 row affected (0.12 sec)
mysql> insert into userLoginInformation(UserName,UserLoginTime) values('Sam','2018-02-19');
Query OK, 1 row affected (0.16 sec)
mysql> insert into userLoginInformation(UserName,UserLoginTime) values('Larry','2017-04-18');
Query OK, 1 row affected (0.18 sec)使用 select 語句從表中顯示所有記錄。
查詢如下
mysql> select *from userLoginInformation;
以下是輸出
+--------+----------+---------------------+ | UserId | UserName | UserLoginTime | +--------+----------+---------------------+ | 1 | John | 2016-02-12 00:00:00 | | 2 | Carol | 2019-01-31 00:00:00 | | 3 | Bob | 2019-02-19 00:00:00 | | 4 | Sam | 2018-02-19 00:00:00 | | 5 | Larry | 2017-04-18 00:00:00 | +--------+----------+---------------------+ 5 rows in set (0.00 sec)
現在,我們將使用 YEAR() 和 now() 根據當前日期篩選記錄。這裡,我們使用 now() 獲得當前日期
mysql> select *from userLoginInformation where YEAR(UserLoginTime)=YEAR(now());
以下是輸出
+--------+----------+---------------------+ | UserId | UserName | UserLoginTime | +--------+----------+---------------------+ | 2 | Carol | 2019-01-31 00:00:00 | | 3 | Bob | 2019-02-19 00:00:00 | +--------+----------+---------------------+ 2 rows in set (0.00 sec)
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP