在Postgres中,如果删除表A中的一行,如何从表B中删除一行?

时间:2016-09-28 14:42:06

标签: postgresql foreign-keys sql-delete cascade

我正在使用Postgres 9.5.0。我有下表

myproject=> \d my_objects;
                                  Table "public.my_objects"
       Column        |            Type             |              Modifiers              
---------------------+-----------------------------+-------------------------------------
 name                | character varying           | 
 day                 | date                        | 
 distance            | double precision            | 
 user_id             | integer                     | 
 created_at          | timestamp without time zone | not null
 updated_at          | timestamp without time zone | not null
 distance_unit_id    | integer                     | 
 import_completed    | boolean                     | 
 id                  | character varying           | not null default uuid_generate_v4()
 linked_my_object_time_id | character varying           | 
 web_crawler_id      | integer                     | 
 address_id          | character varying           | 
Indexes:
    "my_objects_pkey" PRIMARY KEY, btree (id)
    "index_my_objects_on_user_id_and_day_and_name" UNIQUE, btree (user_id, day, name)
    "index_my_objects_on_user_id" btree (user_id)
    "index_my_objects_on_web_crawler_id" btree (web_crawler_id)
Foreign-key constraints:
    "fk_rails_5287d445c0" FOREIGN KEY (address_id) REFERENCES addresses(id) ON DELETE CASCADE
    "fk_rails_970b2325bf" FOREIGN KEY (distance_unit_id) REFERENCES distance_units(id)
    "fk_rails_dda3297b57" FOREIGN KEY (linked_my_object_time_id) REFERENCES my_object_times(id) ON DELETE CASCADE
    "fk_rails_ebd32625bc" FOREIGN KEY (web_crawler_id) REFERENCES web_crawlers(id)
    "fk_rails_fa07601dff" FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE

现在,每个my_object都有一个地址字段。我想要的是当我删除my_object时,也会删除相应的地址条目。如果不将my_objects表中的address_id列移出,是否可以设置一些内容,以便当我从my_objects表中删除一行时,任何相应的地址数据也会被删除?显然,我设置的外键不能完成任务。

1 个答案:

答案 0 :(得分:3)

您可以使用触发器执行此操作:

CREATE OR REPLACE FUNCTION remove_address() RETURNS trigger
   LANGUAGE plpgsql AS
$$BEGIN
   DELETE FROM public.addresses WHERE id = OLD.address_id;
   RETURN OLD;
END;$$;

CREATE TRIGGER remove_address
   AFTER DELETE ON public.my_objects FOR EACH ROW
   EXECUTE PROCEDURE remove_address()