MySQL 怎么做:“今天和今天-7之间”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6276683/
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
How to do : "Between TODAY AND TODAY-7"?
提问by bahamut100
I need to find the account created for the current day, et for the last 7 days.
我需要找到为当天创建的帐户,以及过去 7 天的帐户。
To find my results for today, it works, and I do this :
为了找到我今天的结果,它有效,我这样做:
SELECT * FROM `account` where DATE(created_at) = DATE(NOW())
But I don't know how to do to get the last 7days account.
但我不知道如何获得最后 7 天的帐户。
I tried something like this, but without success :
我尝试过这样的事情,但没有成功:
SELECT * FROM `account` where DATE(created_at) BETWEEN DATE(NOW()) AND DATE(NOW()-7)
Have you an idea ?
你有什么想法吗?
回答by Gryphius
in mysql:
在 mysql 中:
SELECT * FROM `account`
WHERE DATE(created_at) > (NOW() - INTERVAL 7 DAY)
回答by Anne
Try:
尝试:
BETWEEN (NOW() - INTERVAL 7 DAY) AND NOW()
回答by Andriy M
If created_at
has an index and you wouldn't like to prevent the optimiser from using it, I would recommend the following pattern (assuming created_at
contains both date and time):
如果created_at
有索引并且您不想阻止优化器使用它,我会推荐以下模式(假设同时created_at
包含日期和时间):
WHERE created_at >= CURRENT_DATE - INTERVAL 7 DAY
AND created_at < CURRENT_DATE + INTERVAL 1 DAY
This spans the range from the day exactly one week ago till today (inclusive), so 8 days in total.
这跨越了从一周前的那一天到今天(含)的范围,所以总共 8 天。
回答by bw_üezi
also have a look at MySQL functions ADDDATE(), DATE_ADD(), DATE_SUB()
也看看 MySQL 函数 ADDDATE(), DATE_ADD(), DATE_SUB()
e.g.
例如
ADDDATE(DATE(NOW()), -7)