我有一个Items表和Images表。单个项目有多个图像。 如果您看图片:
图像表post_id引用id(来自items)。 (一个帖子可能包含多张图片)
我如何进行SQL查询,该查询将首先删除与帖子关联的所有图像,然后删除帖子。 (基本上,我希望用户能够删除他的帖子。)
Delete from images where post_id = 237;
Delete from items where id = 237;
ERROR: update or delete on table "items" violates foreign key constraint "images_post_id_fkey" on table "images"
DETAIL: Key (id)=(237) is still referenced from table "images".
答案 0 :(得分:1)
尝试:
WITH d
AS
(
DELETE FROM images
WHERE post_id = 240
RETURNING post_id
)
DELETE FROM items
WHERE id = (SELECT DISTINCT
post_id
FROM d);
但是请考虑将images
上的外键约束更改为ON DELETE CASCADE
。这样一来,帖子中的图片就会在删除后自动删除。
请不要发布表格图片。使用CREATE TABLE
和INSERT INTO
语句。