我有很多命令,如:
DELETE FROM table1 WHERE user_id IN (SELECT id FROM users WHERE email LIKE 'abc%');
DELETE FROM table2 WHERE user_id IN (SELECT id FROM users WHERE email LIKE 'abc%');
DELETE FROM table3 WHERE user_id IN (SELECT id FROM users WHERE email LIKE 'abc%');
如何通过变量/ list / array / set中的提取来优化它?
SELECT id FROM users WHERE email LIKE 'abc%'
答案 0 :(得分:3)
如果你的目标是只编写一次只删除一个用户的条件,你可以使用修改CTE的数据:
with user_list as (
select id
from users
where email like 'abc%'
), delete_1 as (
delete from table_1 where user_id in (select id from user_list)
), delete_1 as (
delete from table_2 where user_id in (select id from user_list)
)
delete from table_3 where user_id in (select id from user_list);
您仍然需要为每次删除重复select ...
,但条件需要删除的内容只需在您的对帐单中删除一次。
答案 1 :(得分:2)
您可以将临时表创建为
CREATE TEMP TABLE user_for_delete as
SELECT id
FROM users
WHERE email
LIKE 'abc%';
以及任何其他条件
INSERT INTO user_for_delete (id)
SELECT id
FROM users
WHERE email
LIKE 'cdb%';
最后从table1,2,3
中删除DELETE FROM table1 t
USING user_for_delete u
WHERE u.id = t.user_id
答案 2 :(得分:0)
使用data-modifying CTEs之类的@a_horse suggested。但是从DELETE
statements with the USING
clause中的第一个CTE加入派生表。这有点短而快:
WITH sel AS (SELECT id FROM users WHERE email LIKE 'abc%')
, del1 AS (DELETE FROM table_1 t USING sel WHERE t.user_id = sel.id)
, del2 AS (DELETE FROM table_2 t USING sel WHERE t.user_id = sel.id)
DELETE FROM table_3 t USING sel WHERE t.user_id = sel.id;