简体   繁体   English

Select 对应一个时间的所有行

[英]Select all rows that correspond to a time

I have a script that sends out emails every minute.我有一个每分钟发送电子邮件的脚本。 When it starts its loop, it queries the database for all entries that are equal to the current utc time.当它开始循环时,它会在数据库中查询所有等于当前 UTC 时间的条目。 I would like to have it find all entries in the database that correspond to the current time down to the minute.我想让它找到数据库中与当前时间对应的所有条目,直到分钟。

So there is a 'time' column that stores the utc time: '2009-03-06 20:18:31'.所以有一个“时间”列存储 UTC 时间:“2009-03-06 20:18:31”。 When it searches is there any way to ignore the seconds attribute with out changing how I store the time?当它搜索时,有什么方法可以忽略秒属性而不改变我存储时间的方式?

EDIT: I'm using mysql server.编辑:我正在使用 mysql 服务器。

Thanks!谢谢!

In MySQL :MySQL 中

SELECT *
FROM   table
WHERE  time >= NOW() - INTERVAL EXTRACT(SECOND FROM NOW()) SECOND
       AND time < NOW() - INTERVAL (EXTRACT(SECOND FROM NOW()) + 60) SECOND

This will efficiently use an index on time field.这将有效地使用time字段上的索引。

I've performed this logic before:我之前执行过这个逻辑:

Query for: TimeField >= (Now - 1 Minute).查询:TimeField >=(现在 - 1 分钟)。

You could also modify this logic to query for TimeField >= (Now - # of seconds passed in the current minute) - this might more accurately retrieve what you are looking for.您还可以修改此逻辑以查询 TimeField >= (Now - # of seconds pass in the current minute) - 这可能更准确地检索您要查找的内容。

Make sure you do the calculation on the "now" part of the inequality.确保对不等式的“现在”部分进行计算。 In SQL Server you can use DATEADD(mi, -1, GETDATE()).在 SQL 服务器中,您可以使用 DATEADD(mi, -1, GETDATE())。 If you perform the function on the column, you'll likely end up generating a RBAR operation.如果您在列上执行 function,您最终可能会生成 RBAR 操作。

where datediff(minute, Time, getdate()) = 0

This will work on SQL Server, but as you don't specify what server you're using it's hard to tell if it will work for you.这将适用于 SQL 服务器,但由于您没有指定您使用的服务器,因此很难判断它是否适合您。

this was the actual sql statement that I used.这是我使用的实际 sql 语句。 Notice that it was heavy influenced by Quassnoi's response but there are some key differences.请注意,Quassnoi 的反应对它的影响很大,但也存在一些关键差异。 I used the UTC_TIMESTAMP instead of NOW().我使用了 UTC_TIMESTAMP 而不是 NOW()。

select * 
from table
where time < UTC_TIMESTAMP() + INTERVAL(1) MINUTE  - INTERVAL (EXTRACT(SECOND FROM UTC_TIMESTAMP())) SECOND 
and time >= UTC_TIMESTAMP() - INTERVAL (EXTRACT(SECOND FROM UTC_TIMESTAMP())) SECOND;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM