![](/img/trans.png)
[英]Oracle SQL: update table conditionally based on values in another table
[英]SQL to update an Oracle table based on another table
我在Oracle数据库中有两个表: USERS
和USERLOG
USERS
包含所有系统用户详细信息( IDCOL
, EMAIL
, ISLOCKED
等)
USERLOG
是用户登录系统时的日志( USERID
, LOGIN
(日期字段))
关键字段: USERS.IDCOL
= USERLOG.USERID
已删除的用户将从USERS表中删除; 因此, USERLOG
中将有一些ID与USERS
表不匹配。
我想对用户列表做两件事:
锁定最近9个月内未访问系统的所有用户(即,他们的ID在最近9个月内未出现在USERLOG
中),我想它将使用类似以下内容的方法:
months_between( SYSDATE , USERLOG.LOGIN ) <= 9
USERLOG
只有一个条目的所有用户,只要它不在过去一个月/ 30天内(即创建帐户时)即可 要锁定用户,我需要将USERS.ISLOCKED
列从0
更新为1
非常感谢
months_between(SYSDATE,USERLOG.LOGIN)<= 9
1)在这种情况下,userlog.login不是来自单个行,而是一系列登录中的最大登录时间。 有多种方法可以执行此操作,但是我认为以下查询可以更清楚地捕获需求。 “过去9个月内没有登录的所有用户”
select *
from users usr
where not exists (
select 1
from userlog log
where usr.user_id = log.user_id
and log.login > add_months(sysdate,-9)
)
检查以确保您正在寻找所需的用户,并将此选择转换为删除。
2)这是满足两个规则的2个不同条件。
select *
from users
where not exists (
select 1
from userlog
where users.userid = userlog.userid
and userlog.login > add_months(sysdate,-1)
) AND (
1 = (select count(*)
from userlog
where users.userid = userlog.userid)
)
库伦特测试,但第一个
update users a
set islocked = 1
where exists (
select 1
from userlog b
where a.idcol = b.userid
group by b.userid
having months_betwen(sysdte , max(userlog)) <= 9)
第二个,如果我做对了,您想锁定30天前只有一个入口的用户....如果是,那么
update users set islocked = 1
where idcol in (
select userid
from userlog
group by userid
having count(*) = 1
and count(case when month_between(login , sysdate) < 1 then 1 else null end) = 0)
所以我基本上是在统计上个月和总体的入场人数。 语法可能已关闭,我无法在此处运行示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.