如何在 MySQL 中找出一個月裡有多少天?


要找出一個月裡的天數,請使用以下語法。

select DAY(LAST_DAY(yourColumnName)) as anyVariableName from yourTableName;

為了理解上述語法,我們先建立一個表。建立表的查詢如下。

mysql> create table DaysInaGivenMonth
-> (
-> MonthName datetime
-> );
Query OK, 0 rows affected (1.62 sec)

使用插入命令在表中插入一些記錄。查詢如下。

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)

使用 select 語句從表中顯示所有記錄。查詢如下。

mysql> select *from DaysInaGivenMonth;

以下是輸出內容。

+---------------------+
| 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> select DAY(LAST_DAY(MonthName)) as DaysInMonth from DaysInaGivenMonth;

以下是輸出內容。

+-------------+
| DaysInMonth |
+-------------+
| 31          |
| 31          |
| 30          |
| 31          |
| 30          |
| 31          |
+-------------+
6 rows in set (0.00 sec)

更新於:2019 年 7 月 30 日

5K+ 瀏覽量

開啟您的職業生涯

完成課程以獲得認證

立即開始
廣告
© . All rights reserved.