一般数据库中给到的时间都是年-月-日形式的,那怎么匹配年-月/的形式?
如2021年8月怎么写(怎么在数据库中查询到关于2021年8月的数据):
法一:使用month()函数和year()函数
1 2 3 4 |
select 字段列表 from 表名 where month(date) = 8 and year(date) = 2021; |
法二:like占位符
1 2 3 4 |
select 字段列表 from 表名 where date like '2021-08%'; # %匹配任意个字符 |
法三:substring()函数
1 2 3 4 |
select 字段列表 from 表名 where substring(date,'-',2)='2021-08'; |
法四:
1 2 3 4 |
select 字段列表 from 表名 where date>='2021-08-01' and date<='2021-08-31'; |
法五:
1 2 3 4 |
select 字段列表 from 表名 where date between '2021-08-01' and '2021-08-31'; |
补充:
MySql查询语句根据年份或月份查询
1. 按年份查询
1 |
select 字段名 from 表 where year(字段名)='年份'; |
2. 按月份查询:
1 |
select 字段名 from 表 where month(字段名)='月份'; |
3. 查本年的某一天(例本年的第6天)
1 |
select 字段名 from 表 where dayofyear(字段名)='6'; |