MySQL where date 大于一个月?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4237594/
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
MySQL Where date is greater than one month?
提问by JasonS
I have a datetime column called 'last_login'.
我有一个名为“last_login”的日期时间列。
I want to query my database to select all records that haven't logged in within the last month. How do I do this?
我想查询我的数据库以选择上个月内未登录的所有记录。我该怎么做呢?
This is what I have currently:
这是我目前所拥有的:
$query = $this->query("SELECT u.id, u.name, u.email, u.registered, g.name as group_name FROM `:@users` AS u LEFT JOIN `:@groups` AS g on u.group_id = g.id WHERE u.last_login = ...... LIMIT {$limit_start}, {$limit_end}");
:@ = database prefix
:@ = 数据库前缀
回答by Matt Healy
Try using date_sub
尝试使用 date_sub
where u.last_login < date_sub(now(), interval 1 month)
(Similar to the first answer but in my mind it is more "natural" to use positive integers)
(类似于第一个答案,但在我看来,使用正整数更“自然”)
回答by T.J. Crowder
You can use date_add
combined with now
:
...where u.last_login < date_add(now(), interval -1 month)
Naturally, as both are MySQL-specific this limits you to MySQL backends. Alternately, you can figure out what the date was a month ago with PHP (I'm not a PHP person, but I'm guessing DateTime::sub
would help with that) and then include that date in your query in the normal way you would any other date/time field.
自然地,由于两者都是 MySQL 特定的,这将您限制在 MySQL 后端。或者,您可以使用 PHP 找出一个月前的日期(我不是 PHP 人,但我猜DateTime::sub
这会有所帮助),然后以正常方式将该日期包含在您的查询中日期/时间字段。
回答by delta5
matthewh was almost correct, except the >
should have been a right one.
matthewh 几乎是正确的,除了>
应该是正确的。
where u.last_login > date_sub(now(), interval 1 month)
where u.last_login > date_sub(now(), interval 1 month)