我们可以在 MySQL 中根据 DATEPART() 来选择行吗?这是可能的?
MySQL 中没有 DATEPART() 函数,你需要使用 MONTH() 函数来从日期列中提取月份名称。语法如下
SELECT *FROM yourTableName WHERE MONTH(yourDateColumnName)=yourValue;
为了理解上述语法,让我们创建一个表。创建表的查询如下
mysql> create table SelectRowFromDatePart -> ( -> Id int NOT NULL AUTO_INCREMENT, -> LoginDate date, -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (2.42 sec)
现在你可以使用插入命令在表中插入一些记录。查询如下
mysql> insert into SelectRowFromDatePart(LoginDate) values(curdate()); Query OK, 1 row affected (0.21 sec) mysql> insert into SelectRowFromDatePart(LoginDate) values(date_add(curdate(),interval -3 year)); Query OK, 1 row affected (0.19 sec) mysql> insert into SelectRowFromDatePart(LoginDate) values('2014-05-21'); Query OK, 1 row affected (0.21 sec) mysql> insert into SelectRowFromDatePart(LoginDate) values('2015-08-25'); Query OK, 1 row affected (0.23 sec) mysql> insert into SelectRowFromDatePart(LoginDate) values('2018-12-31'); Query OK, 1 row affected (0.18 sec) mysql> insert into SelectRowFromDatePart(LoginDate) values('2011-12-21'); Query OK, 1 row affected (0.21 sec) mysql> insert into SelectRowFromDatePart(LoginDate) values('2013-10-02'); Query OK, 1 row affected (0.12 sec) mysql> insert into SelectRowFromDatePart(LoginDate) values('2006-12-11'); Query OK, 1 row affected (0.17 sec) mysql> insert into SelectRowFromDatePart(LoginDate) values('2010-03-09'); Query OK, 1 row affected (0.40 sec) mysql> insert into SelectRowFromDatePart(LoginDate) values('2012-12-12'); Query OK, 1 row affected (0.70 sec)
使用 select 语句显示表中的所有记录。查询如下
mysql> select *from SelectRowFromDatePart;
下面是输出
+----+------------+ | Id | LoginDate | +----+------------+ | 1 | 2019-01-31 | | 2 | 2016-01-31 | | 3 | 2014-05-21 | | 4 | 2015-08-25 | | 5 | 2018-12-31 | | 6 | 2011-12-21 | | 7 | 2013-10-02 | | 8 | 2006-12-11 | | 9 | 2010-03-09 | | 10 | 2012-12-12 | +----+------------+ 10 rows in set (0.00 sec)
以下是通过 datepart(即 MONTH())选择行的查询
mysql> select *from SelectRowFromDatePart where MONTH(LoginDate)=12;
下面是输出
+----+------------+ | Id | LoginDate | +----+------------+ | 5 | 2018-12-31 | | 6 | 2011-12-21 | | 8 | 2006-12-11 | | 10 | 2012-12-12 | +----+------------+ 4 rows in set (0.00 sec)
广告