当前位置:  开发笔记 > 后端 > 正文

SQLite中的级联触发器

如何解决《SQLite中的级联触发器》经验,为你挑选了1个好方法。

我在SQLite中有以下数据库结构:

数据库结构http://i39.tinypic.com/kb3qef.jpg

我想创建一个触发器,每当我删除一个国家时,所有相关的区域,市政和教区也被删除(如MySQL InnoDB),我尝试使用SQLite触发器并想出了这个:

区:

CREATE TRIGGER [delete_country]
BEFORE DELETE
ON [countries]
FOR EACH ROW
BEGIN
DELETE FROM districts WHERE districts.id_countries = id;
END

市政:

CREATE TRIGGER [delete_district]
BEFORE DELETE
ON [districts]
FOR EACH ROW
BEGIN
DELETE FROM municipalities WHERE municipalities.id_districts = id;
END

教区:

CREATE TRIGGER [delete_municipality]
BEFORE DELETE
ON [municipalities]
FOR EACH ROW
BEGIN
DELETE FROM parishes WHERE parishes.id_municipalities = id;
END

我还没有对触发器进行测试delete_district,delete_municipality因为我在delete_country触发器上遇到了一个奇怪的行为:当我删除一个国家时,只有第一个相关的区域被删除,所有其他相关的区域仍然在表中.我究竟做错了什么?



1> UncleO..:

触发器看起来正在删除id等于id_countries的区域,即where子句实际上是

WHERE districts.id_countries = districts.id

您需要引用countries表中的id.在删除触发器中,使用"old"执行此操作.

CREATE TRIGGER [delete_country]
BEFORE DELETE
ON [countries]
FOR EACH ROW
BEGIN
DELETE FROM districts WHERE districts.id_countries = old.id;
END

另外,我建议更改架构命名约定.通常,表名是单数,并且对应于行中的实体.我会有一个包含列id和名称的国家/地区表,一个包含id,country_id和name等的分区表.

country
-------
id
name

district
-------
id
country_id
name

municipality
------------
id
district_id
name

parish
-----
id
municipality_id
name

那么触发器就是

CREATE TRIGGER [delete_country]
BEFORE DELETE
ON [country]
FOR EACH ROW
BEGIN
DELETE FROM district WHERE district.country_id = old.id;
END

推荐阅读
ERIK又
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有