在单个语句中从多个表中删除行
Delete rows from multiple tables in a single statement
我有 2 个表 users
和 articles
,我还需要从文章中删除一个用户和该用户的所有实例,但我需要在一条语句中完成.所以我不能说:
DELETE FROM users WHERE id = 1
DELETE FROM articles WHERE user_id = 1
有没有办法让我可以这样说:
SELECT u.name, u.id, a.user_id
FROM users u, articles a
WHERE u.id = a.user_id
DELETE FROM thistable
WHERE id = 1
如有任何帮助,我们将不胜感激
这样做的标准方法是将外键声明为 ON DELETE CASCADE
。这样做,如果一个 user
被删除,所有与它相关的 articles
也将被删除。
CREATE TABLE articles (
user_id int REFERENCES users (id) ON DELETE CASCADE);
演示:db<>fiddle
如果由于某种原因您无法更改 table 结构,请考虑在 CTE 中使用来自 users
的 DELETE ... RETURNING
,然后在外部使用返回值DELETE
在 articles
:
WITH j (id) AS (
DELETE FROM users WHERE id = 1
RETURNING id
)
DELETE FROM articles a USING j
WHERE a.user_id = j.id;
演示:db<>fiddle
我有 2 个表 users
和 articles
,我还需要从文章中删除一个用户和该用户的所有实例,但我需要在一条语句中完成.所以我不能说:
DELETE FROM users WHERE id = 1
DELETE FROM articles WHERE user_id = 1
有没有办法让我可以这样说:
SELECT u.name, u.id, a.user_id
FROM users u, articles a
WHERE u.id = a.user_id
DELETE FROM thistable
WHERE id = 1
如有任何帮助,我们将不胜感激
这样做的标准方法是将外键声明为 ON DELETE CASCADE
。这样做,如果一个 user
被删除,所有与它相关的 articles
也将被删除。
CREATE TABLE articles (
user_id int REFERENCES users (id) ON DELETE CASCADE);
演示:db<>fiddle
如果由于某种原因您无法更改 table 结构,请考虑在 CTE 中使用来自 users
的 DELETE ... RETURNING
,然后在外部使用返回值DELETE
在 articles
:
WITH j (id) AS (
DELETE FROM users WHERE id = 1
RETURNING id
)
DELETE FROM articles a USING j
WHERE a.user_id = j.id;
演示:db<>fiddle