1

如何创建一个与另一个共享公共 id 的表,以及一旦从第一个表中删除哪一行?

我听说过 FOREIGN KEY, REFERENCES 但不确定如何实际创建此类表。有什么例子可以让我开始吗?

4

1 回答 1

2

我认为您要么在谈论级联删除,要么在谈论您不应该做的非常奇怪的事情。:)

外键信息: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

编辑:添加示例:

表创建:

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)
);

触发级联删除的示例:

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.
于 2013-01-04T16:50:22.117 回答