MySQL 获取上一小时添加的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3681345/
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
Fetching rows added last hour
提问by Michael Grons
I keep a record of logins in a table. I have columns for id, ip, date and time. From that record of logins I wanna fetch logins made only in the last hour.
我将登录记录保存在表中。我有 id、ip、日期和时间的列。从登录记录中,我想获取仅在过去一小时内进行的登录。
I'm sweeping through the MySQL docs on time and date functions, but I just can't seem to combine them correctly.
我正在浏览有关时间和日期函数的 MySQL 文档,但我似乎无法正确组合它们。
Can somebody help me?
有人可以帮助我吗?
回答by SDReyes
Make use of the DATE_SUB() and Now() functions:
利用 DATE_SUB() 和 Now() 函数:
select count(*) as cnt
from log
where date >= DATE_SUB(NOW(),INTERVAL 1 HOUR);
Hope it helps you : )
希望对你有帮助:)
回答by phoenix
If you want to implement this into a cronjob, you need to specify the start and end.
如果要将其实现到 cronjob 中,则需要指定开始和结束。
For example, at 2pm, if you want to get the data for the past hour from 13:00:00 until 13:59:59, here's how to do it:
例如,在下午 2 点,如果您想获取过去一小时 13:00:00 到 13:59:59 的数据,请执行以下操作:
dateField BETWEEN
DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 HOUR), '%Y-%m-%d %H:00:00')
AND
DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 HOUR), '%Y-%m-%d %H:59:59')
回答by Paul Schreiber
I recommend have one datetime column instead of date and time columns.
我建议使用一个日期时间列而不是日期和时间列。
Suppose you have a datetime column called last_login:
假设您有一个名为 last_login 的日期时间列:
SELECT id, ip_address, last_login
FROM mytable
WHERE last_login >= DATE_SUB(NOW(), interval 1 hour);
回答by Varun Nath
it can be done easily using
它可以很容易地使用
select count(*) from logins where datetime>= NOW()- INTERVAL 1 HOUR
回答by Faisal
You can also use CURDATE()function
您还可以使用 CURDATE() 函数
SELECT
count(*) AS TotalCount
FROM
tblName
WHERE
datetime >= DATE_SUB(CURDATE(), INTERVAL 1 HOUR)
回答by DRapp
without the specifics, I think Date_Add() would work.. by adding to your where clause an add of NOW negative hours
没有具体细节,我认为 Date_Add() 会起作用..通过在您的 where 子句中添加 NOW 负小时数
(or Date_Sub() )
(或 Date_Sub() )