Select 按月 sql

Select by month sql

我有这个日期 2021-08-19, 我想按月 select 我的 table 中的所有数据,其中 dateC =(提取月份)。 示例查询

SELECT * FROM MYTABLE WHERE dateC= extract month "08" from(2021-08-19)

您可以使用:

where year(dateC) = year('2021-08-19') and
      month(dateC) = month('2021-08-19')

如果您只想要月份而不考虑年份,那么:

where month(dateC) = month('2021-08-19')

where date_format(dateC, '%Y%m') = date_format('2021-08-19', '%Y%m')

这些都不是索引友好的。这需要更多的工作。让我们打电话给你的约会对象 @date:

where dateC >= @date + interval (1 - day(@date)) day and
      dateC < (@date + interval (1 - day(@date)) day) + interval 1 month

注意:如果有时间组件,以上所有工作。如果 dateC 真的是一个没有时间成分的日期,那么:

where dateC > last_day(@date - interval 1 month) and
      dateC <= last_day(@date)