当仅存在单个特定关系时删除行



我有一个带有uidemail的表格person。 我还有一个表格parent_child用于存储父母关系。 它有 parent_uidchild_uid ,它们都是对personuid的必需引用。

当我删除一个person时,我想删除所有子项,只要:

  1. 孩子没有设置电子邮件。 由于我在其他地方如何使用此字段,我只是为此检查@符号。
  2. 孩子没有其他父母。

现在我正在尝试从BEFORE DELETE ON person触发器执行此操作,但我觉得这不是处理此问题的最有效方法。

FOR child IN SELECT DISTINCT child_uid FROM parent_child WHERE parent_uid = OLD.uid
LOOP
    IF NOT EXISTS (
        -- Any parent that is not me.
        SELECT 1
        FROM parent_child
        WHERE child_uid = child AND parent_uid <> OLD.uid
    ) THEN
        DELETE FROM person WHERE uid = child AND email NOT LIKE '%@%'
    END IF;
END LOOP;

没有比触发器更好的方法了。

为了提高效率,您将索引person(uid)parent(parent_uid)parent_child(child_uid)(后一个索引应该是不必要的,因为您将对parent_uidchild_uid具有主键约束(。

最新更新