當日期為 varchar 時,如何在 MySQL 中過濾指定月份?
要進行過濾,可以使用 MySQL 中的 STR_TO_DATE() 函式。除此之外,使用 MONTH() 來獲取指定月份中的日期。讓我們首先建立一個表 −
mysql> create table DemoTable -> ( -> DueDate varchar(100) -> ); Query OK, 0 rows affected (1.18 sec)
使用 insert 命令往表中插入一些記錄 −
mysql> insert into DemoTable values('06-19-2019'); Query OK, 1 row affected (0.36 sec) mysql> insert into DemoTable values('01-31-2018'); Query OK, 1 row affected (0.38 sec) mysql> insert into DemoTable values('12-01-2016'); Query OK, 1 row affected (0.14 sec)
使用 select 語句從表中顯示所有記錄 −
mysql> select *from DemoTable;
輸出
將生成以下輸出 −
+------------+ | DueDate | +------------+ | 06-19-2019 | | 01-31-2018 | | 12-01-2016 | +------------+ 3 rows in set (0.00 sec)
以下是當日期為 varchar 時在 MySQL 中過濾月份的查詢 −
mysql> select *from DemoTable -> where month(str_to_date(DueDate, '%m-%d-%Y')) = 06;
輸出
將生成以下輸出 −
+------------+ | DueDate | +------------+ | 06-19-2019 | +------------+ 1 row in set (0.00 sec)
廣告