我有一个带有uid
和email
的表格person
。 我还有一个表格parent_child
用于存储父母关系。 它有 parent_uid
和 child_uid
,它们都是对person
表uid
的必需引用。
当我删除一个person
时,我想删除所有子项,只要:
- 孩子没有设置电子邮件。 由于我在其他地方如何使用此字段,我只是为此检查@符号。
- 孩子没有其他父母。
现在我正在尝试从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_uid
和child_uid
具有主键约束(。