Oracle SQL 使用 having 子句删除 table 条目
Oracle SQL to delete table entries using having clause
我有一个 SQL 查询,它根据上次登录日期 table 查找用户标识
select USER_ID, max(login_time) maxd from MyTable group by User_Id having max(login_time) < (sysdate - 90)
我需要删除此查询找到的条目
我试过了
DELETE a
FROM MyTable a
JOIN
(
select USER_ID, max(login_time) maxd from MyTable group by User_Id having max(login_time) < (sysdate - 90)
) b ON a.USER_ID = b.USER_ID
但这导致
SQL 错误:ORA-00933:SQL 命令未正确结束
有人能帮忙吗?
使用您的 select
作为子查询:
DELETE FROM MyTable
WHERE (user_id, login_time) IN
-- this is your query:
( SELECT USER_ID, MAX (login_time) maxd
FROM MyTable
GROUP BY User_Id
HAVING MAX (login_time) < (SYSDATE - 90));
Oracle 支持 delete join 语法,但与其他数据库有点不同。
DELETE FROM (
SELECT a.*
FROM MyTable a
INNER JOIN
(
SELECT USER_ID
FROM MyTable
GROUP BY User_Id
HAVING MAX(login_time) < (sysdate - 90)
) b ON a.USER_ID = b.USER_ID
);
您可以关联 ROWID
伪列并使用分析函数:
DELETE FROM mytable
WHERE ROWID IN (
SELECT ROWID
FROM (
SELECT login_time,
MAX(login_time) OVER (PARTITION BY user_id) AS max_login_time
FROM mytable
)
WHERE max_login_time < SYSDATE - INTERVAL '90' DAY
AND login_time = max_login_time
)
我有一个 SQL 查询,它根据上次登录日期 table 查找用户标识
select USER_ID, max(login_time) maxd from MyTable group by User_Id having max(login_time) < (sysdate - 90)
我需要删除此查询找到的条目
我试过了
DELETE a
FROM MyTable a
JOIN
(
select USER_ID, max(login_time) maxd from MyTable group by User_Id having max(login_time) < (sysdate - 90)
) b ON a.USER_ID = b.USER_ID
但这导致 SQL 错误:ORA-00933:SQL 命令未正确结束
有人能帮忙吗?
使用您的 select
作为子查询:
DELETE FROM MyTable
WHERE (user_id, login_time) IN
-- this is your query:
( SELECT USER_ID, MAX (login_time) maxd
FROM MyTable
GROUP BY User_Id
HAVING MAX (login_time) < (SYSDATE - 90));
Oracle 支持 delete join 语法,但与其他数据库有点不同。
DELETE FROM (
SELECT a.*
FROM MyTable a
INNER JOIN
(
SELECT USER_ID
FROM MyTable
GROUP BY User_Id
HAVING MAX(login_time) < (sysdate - 90)
) b ON a.USER_ID = b.USER_ID
);
您可以关联 ROWID
伪列并使用分析函数:
DELETE FROM mytable
WHERE ROWID IN (
SELECT ROWID
FROM (
SELECT login_time,
MAX(login_time) OVER (PARTITION BY user_id) AS max_login_time
FROM mytable
)
WHERE max_login_time < SYSDATE - INTERVAL '90' DAY
AND login_time = max_login_time
)