MySQL MySQL选择昨天的日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15622803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 17:02:23  来源:igfitidea点击:

MySQL select yesterday's date

mysqlsqldate

提问by Richard Rodriguez

If I have a date like this:

如果我有这样的约会:

'2013-03-25'

And I want to write a MySQL query with WHEREis "yesterday", how do I do it?

我想用WHERE“昨天”写一个 MySQL 查询,我该怎么做?

回答by John Conde

This should do it:

这应该这样做:

WHERE `date` = CURDATE() - INTERVAL 1 DAY

回答by Simon Dorociak

A simple way to get yesterday's date is to use subdate()function:

获取昨天日期的一种简单方法是使用subdate()函数:

subdate(currentDate, 1)

回答by Elliot Larson

I always have to refer to a code snippet to wrap my head around this again.

我总是不得不参考一个代码片段来再次解决这个问题。

It's customary to store datetimes in UTC in the database. But usually, when generating reports, the times need to be adjusted for a specific timezone.

习惯上将日期时间以 UTC 格式存储在数据库中。但通常,在生成报告时,需要针对特定​​时区调整时间。

Here's the snippet I use to show selecting yesterday, adjusted for Pacific time:

这是我用来显示昨天选择的片段,根据太平洋时间进行了调整:

SET @date_start = DATE_SUB((CURDATE() - INTERVAL 1 DAY), INTERVAL 8 HOUR);
SET @date_end = DATE_SUB(CURDATE(), INTERVAL 8 HOUR);

SELECT
    projects.token,
    projects.created_at as 'UTC created_at',
    DATE_SUB(projects.created_at, INTERVAL 8 HOUR) as 'Pacific created_at'
FROM
    projects
WHERE
    projects.created_at BETWEEN @date_start AND @date_end;

Note:I set the variables in the snippet so it's easier to look at. When I write the final query, I usually don't use the variables.

注意:我在代码段中设置了变量,以便更容易查看。当我编写最终查询时,我通常不使用变量。

回答by Kris

I think you're looking for:

我认为您正在寻找:

DATE_ADD(date_column, INTERVAL -1 DAY)

see https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html

https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html