如何创建一个与另一个表共享公用标识的表,并且一旦从第一个表中删除了哪个表,将删除这两个表中的表 [英] How to create one table which shares common id with another and which row gets removed in both tables once it's removed from first
问题描述
如何创建一个与另一个表共享公用标识的表,以及在哪个表从第一个表中删除哪个表?
How to create one table which shares common id with another and which row gets removed in both tables once it's removed from first?
我听说过FOREIGN KEY,REFERENCES但不知道如何实际创建这样的表。
任何例子,让我开始?
I heard about FOREIGN KEY, REFERENCES but not sure how to actually create such tables. Any example to get me started?
推荐答案
我想你是在谈论一个级联删除或真的奇怪你不应该这样做。 :)
I think you're either talking about a cascading delete or something really weird that you shouldn't do. :)
外键信息: http://www.postgresql.org/docs/8.3/static/tutorial-fk.html
关于级联删除的信息(搜索ON DELETE CASCADE页面): http:// www。 postgresql.org/docs/8.2/static/ddl-constraints.html
Info on cascading deletes (search the page for "ON DELETE CASCADE"): http://www.postgresql.org/docs/8.2/static/ddl-constraints.html
编辑:新增示例:
创建表:
Table creation:
CREATE TABLE products (
product_no integer PRIMARY KEY,
name text,
price numeric
);
CREATE TABLE orders (
order_id integer PRIMARY KEY,
shipping_address text,
...
);
CREATE TABLE order_items (
product_no integer REFERENCES products ON DELETE RESTRICT,
order_id integer REFERENCES orders ON DELETE CASCADE,
quantity integer,
PRIMARY KEY (product_no, order_id)
);
触发级联删除的示例:
Example of triggering cascading delete:
DELETE FROM orders -- This will delete all orders with
WHERE order_id BETWEEN 1 AND 10 ; -- order_id between 1 and 10 and
-- all associated order items.
这篇关于如何创建一个与另一个表共享公用标识的表,并且一旦从第一个表中删除了哪个表,将删除这两个表中的表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!