简体   繁体   English

Oracle:如何更新表中的“过时”日期?

[英]Oracle: how to update “outdated” date in table?

Our use case : 我们的用例

For table USERS : 对于表USERS

update all rows (set value 'N' for column ACTIVE ) in case when user was inactive (column 'LAST_VISIT' ) more that 60 minutes. 如果用户处于非活动状态(列'LAST_VISIT' )超过60分钟,请更新所有行(列ACTIVE设置值'N' )。

Google helped me to find how to obtain current time in db (I use Oracle ): Google帮助我找到了如何获取db中的当前时间(我使用Oracle ):

SELECT sysdate FROM dual;

Then I found the way how to find the difference in minutes between two dates: 然后,我找到了一种方法来查找两个日期之间的分钟数差异:

SELECT(date1 - date2)*1440

Looks like a little bit ugly... but ok. 看起来有点难看...但是还可以。

Now, I am trying to combine all together: 现在,我尝试将所有内容组合在一起:

UPDATE USERS u 
SET ACTIVE='N' 
WHERE  SELECT((SELECT sysdate FROM dual) - u.LAST_VISIT)*1440 >60;

Could you please review my final query. 您能否检查一下我的最终查询。

Is it ok? 可以吗 Or, maybe, it is possible to optimize it? 或者,也许可以对其进行优化?

You can simplify the query 您可以简化查询

UPDATE users u
   SET active = 'N'
 WHERE u.last_visit < sysdate - interval '1' hour;

If there is an index on last_visit that can be used for the query (because the predicate is sufficiently selective), this query can potentially use that index. 如果last_visit上有一个可用于查询的索引(因为谓词具有足够的选择性),则该查询可能会使用该索引。

Justin's answer is very good, but it will probably update too many rows. 贾斯汀的答案很好,但是可能会更新太多行。 You should add an extra condition to the where clause: 您应该在where子句中添加一个附加条件:

UPDATE users u
   SET active = 'N'
    WHERE active <> 'N' AND u.last_visit < sysdate - interval '1' hour;

This saves the attempted update for users who are already inactive. 这样可以为已经不活动的用户保存尝试进行的更新。 (Note: this version assumes that active does not take the value of NULL .) (注意:此版本假定active不采用NULL 。)

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

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