我在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
触发器上遇到了一个奇怪的行为:当我删除一个国家时,只有第一个相关的区域被删除,所有其他相关的区域仍然在表中.我究竟做错了什么?
触发器看起来正在删除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