MySQL 如何找到一个月的天数
要找到月份的天数,请使用以下语法。
select DAY(LAST_DAY(yourColumnName)) as anyVariableName from yourTableName;
Mysql
为了理解上述语法,让我们首先创建一个表。创建一个表的查询语句如下。
mysql> create table DaysInaGivenMonth
-> (
-> MonthName datetime
-> );
Query OK, 0 rows affected (1.62 sec)
Mysql
使用插入命令在表中插入一些记录。查询语句如下。
mysql> insert into DaysInaGivenMonth values(now());
Query OK, 1 row affected (0.24 sec)
mysql> insert into DaysInaGivenMonth values(date_add(now(),interval -1 month));
Query OK, 1 row affected (0.16 sec)
mysql> insert into DaysInaGivenMonth values(date_add(now(),interval -2 month));
Query OK, 1 row affected (0.10 sec)
mysql> insert into DaysInaGivenMonth values(date_add(now(),interval -3 month));
Query OK, 1 row affected (0.20 sec)
mysql> insert into DaysInaGivenMonth values(date_add(now(),interval -4 month));
Query OK, 1 row affected (0.23 sec)
mysql> insert into DaysInaGivenMonth values(date_add(now(),interval -5 month));
Query OK, 1 row affected (0.15 sec)
Mysql
使用select语句显示表中的所有记录。查询语句如下。
mysql> select *from DaysInaGivenMonth;
Mysql
输出如下。
+---------------------+
| MonthName |
+---------------------+
| 2019-01-01 21:34:26 |
| 2018-12-01 21:34:55 |
| 2018-11-01 21:35:14 |
| 2018-10-01 21:35:20 |
| 2018-09-01 21:35:23 |
| 2018-08-01 21:35:27 |
+---------------------+
6 rows in set (0.00 sec)
Mysql
以下是查找上述月份的天数的查询语句。
mysql> select DAY(LAST_DAY(MonthName)) as DaysInMonth from DaysInaGivenMonth;
Mysql
输出如下。
+-------------+
| DaysInMonth |
+-------------+
| 31 |
| 31 |
| 30 |
| 31 |
| 30 |
| 31 |
+-------------+
6 rows in set (0.00 sec)
Mysql
阅读更多:MySQL 教程