1. 使用到的 MySQL 日期函數:
函數 | 功能 |
DATE_FORMAT(date, fnt) | 返回按字符串 fmt 格式化的日期 date 值 |
格式符 | 格式說明 |
%Y | 四位數字表示的年份,如:2016、2017、2018...(注意 Y 爲大寫) |
%m | 兩位數字表示的月份,如:01、02、03...(注意 m 爲小寫) |
mysql> select DATE_FORMAT(NOW(), '%Y%m'); -- 將當前時間轉爲年月格式
+----------------------------+
| DATE_FORMAT(NOW(), '%Y%m') |
+----------------------------+
| 201603 |
+----------------------------+
1 row in set (0.00 sec)
本例中數據庫表結構:
mysql> desc blog.blog_article;
+-------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------------+--------------+------+-----+---------+----------------+
| _id | int(11) | NO | PRI | NULL | auto_increment |
| _content | text | NO | | NULL | |
| _create_time | datetime | YES | | NULL | |
| _is_allow_comment | bit(1) | YES | | b'1' | |
| _is_delete | bit(1) | YES | | b'0' | |
| _order | int(11) | YES | | NULL | |
| _title | varchar(255) | NO | | NULL | |
| _author | int(11) | YES | MUL | NULL | |
+-------------------+--------------+------+-----+---------+----------------+
8 rows in set (0.03 sec)
mysql> select * from blog.blog_article \G;
*************************** 1. row ***************************
_id: 1
_content: <p>這是文章一。</p>
_create_time: 2016-01-03 13:26:57
_is_allow_comment:
_is_delete:
_order: 0
_title: 文章一
_author: 1
*************************** 2. row ***************************
_id: 2
_content: <p>這是文章二。</p>
_create_time: 2016-03-11 19:40:06
_is_allow_comment:
_is_delete:
_order: 0
_title: 文章二
_author: 1
*************************** 3. row ***************************
_id: 3
_content: <p>這是文章三。</p>
_create_time: 2016-03-15 20:12:50
_is_allow_comment:
_is_delete:
_order: 0
_title: 文章三
_author: 1
3 rows in set (0.00 sec)
mysql> select distinct DATE_FORMAT(a._create_time, '%Y%m') from blog.blog_article as a order by a._create_time DESC;
+-------------------------------------+
| DATE_FORMAT(a._create_time, '%Y%m') |
+-------------------------------------+
| 201603 |
| 201601 |
+-------------------------------------+
2 rows in set (0.00 sec)
mysql> select distinct DATE_FORMAT(a._create_time, '%Y年%m月') from blog.blog_article as a order by a._create_time DESC;
+-------------------------------------------+
| DATE_FORMAT(a._create_time, '%Y年%m月') |
+-------------------------------------------+
| 2016年03月 |
| 2016年01月 |
+-------------------------------------------+
2 rows in set (0.00 sec)
3. 查詢 _create_time 在 2016 年 3 月份的數據;
mysql> select * from blog.blog_article as a where DATE_FORMAT(a._create_time, '%Y%m') = '201603' \G;
*************************** 1. row ***************************
_id: 2
_content: <p>這是文章二。</p>
_create_time: 2016-03-11 19:40:06
_is_allow_comment:
_is_delete:
_order: 0
_title: 文章二
_author: 1
*************************** 2. row ***************************
_id: 3
_content: <p>這是文章三。</p>
_create_time: 2016-03-15 20:12:50
_is_allow_comment:
_is_delete:
_order: 0
_title: 文章三
_author: 1
2 rows in set (0.00 sec)