有我的桌子:
create table location (
nom text primary key,
adresse text
);
create table groupe (nom text primary key);
create table groupelocation (
nomGroupe text references groupe (nom) on delete cascade,
nomLocation text references location (nom) on delete cascade,
primary key(nomGroupe, nomLocation)
);
insert into groupe values('groupe');
insert into location values('location', 'là bas');
insert into groupelocation values('groupe', 'location');
我希望当我删除组表中的somethng时,删除所有关联的位置,但我找不到解决方案:/
我试过这样做:create rule deletelocations as on delete to groupe do instead (delete from (select location natural join groupelocation where old.nom = nomGroupe));
但这不起作用:/你能帮我吗?
答案 0 :(得分:0)
Postgres不支持将CASCADE提供给DELETE语句,但它支持在表创建时级联删除。
http://www.postgresql.org/docs/9.0/static/sql-createtable.html
CASCADE删除引用已删除行的所有行,或更新 引用列的值为引用的新值 专栏。
答案 1 :(得分:0)
有一个解决方案,我已经创建了一个小的plpgsql函数来解决这个问题
CREATE OR REPLACE FUNCTION deletelocation()
RETURNS text AS $$
DECLARE
idloc int;
curs refcursor;
BEGIN
OPEN curs FOR SELECT location.id FROM location except SELECT location.id FROM location JOIN groupelocation ON location.id = groupelocation.idLocation;
LOOP
FETCH curs INTO idloc;
EXIT WHEN NOT FOUND;
DELETE FROM location WHERE id = idloc;
END LOOP;
CLOSE curs;
RETURN '';
END;
$$ language plpgsql;