【问题标题】:MySQL Select Values from Jan 1 to yesterdayMySQL 选择值从 1 月 1 日到昨天
【发布时间】:2020-09-25 21:22:12
【问题描述】:

我有三段不同的代码。一个选择昨天(上午 12 点到晚上 11 点 59 分)的所有值。下一个选择从当前月份开始的所有值(在本例中为 9 月 1 日上午 12 点到 9 月 24 日晚上 11:59)。第三个是“应该”选择从年初(1/1 上午 12 点到 9 月 24 日晚上 11:59)的所有值。但是,我做错了,因为它从一开始(2016 年中)就采用了所有值。请让我知道我做错了什么。

昨天:

select LogDateTime, UVindex 
from monthly_new 
where LogDateTime between current_date - interval 1 day and current_date;

本月:

select LogDateTime, UVindex 
from monthly_new 
where LogDateTime between current_date - dayofmonth(current_date) + 1 and current_date;

今年(不工作):

select LogDateTime, UVindex 
from monthly_new 
where LogDateTime between current_date - dayofyear(current_date) + 1 and current_date;

【问题讨论】:

    标签: mysql sql datetime where-clause


    【解决方案1】:

    我喜欢为此使用date_format();它可以轻松截断为月或年,并利用 MySQL 的灵活性将字符串视为日期。

    过滤从年初到今天:

     LogDateTime between date_format(current_date, '%Y-01-01') and current_date
    

    从月初开始:

     LogDateTime between date_format(current_date, '%Y-%m-01') and current_date
    

    【讨论】:

    • 啊,我明白了。月份查询有效,所以我可能会保留它们,但今年正是我需要的。谢谢!
    猜你喜欢
    • 2013-03-15
    • 2020-06-07
    • 1970-01-01
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多