繁体   English   中英

运行带约束的数据库创建脚本

[英]Running database creation script with constraints

我创建了一个表模式,但我不知道在这种情况下我应该如何运行脚本,因为我对需要创建其他表的每个表都有约束,是否有任何方法可以在创建后添加约束或其他方法在脚本中保持正确的表模式相等?

我使用 PostgreSQL 作为数据库。

CREATE TABLE IF NOT EXISTS store (
    id INTEGER NOT NULL,
    nome VARCHAR(255) NOT NULL,
    document VARCHAR(80) NOT NULL,
    store_product INTEGER NOT NULL,
    PRIMARY KEY (id),
    FOREIGN KEY (store_product) REFERENCES product (id)
);

CREATE TABLE IF NOT EXISTS product (
    id INTEGER NOT NULL,
    nome VARCHAR(255) NOT NULL,
    price NUMERIC(15,2) NOT NULL,
    store_id INTEGER NOT NULL,
    inventory_id INTEGER NOT NULL,
    PRIMARY KEY (id),
    FOREIGN KEY (store_id) REFERENCES store (id),
    FOREIGN KEY (inventory_id) REFERENCES inventory (id)
);

CREATE TABLE IF NOT EXISTS inventory (
    id INTEGER NOT NULL PRIMARY KEY,
    amount INTEGER NOT NULL,
    product_id INTEGER NOT NULL,
    FOREIGN KEY (product_id) REFERENCES product (id)
);

首先创建没有外键约束的表,然后将其更改为外键,这将是一种解决方法

外键约束有两个问题:

1.添加约束

当存在循环链接表子集的 FK 时,您可以先创建表,然后再添加约束。

例如:

CREATE TABLE store (
    id INTEGER NOT NULL,
    nome VARCHAR(255) NOT NULL,
    document VARCHAR(80) NOT NULL,
    store_product INTEGER NOT NULL,
    PRIMARY KEY (id)
);

CREATE TABLE product (
    id INTEGER NOT NULL,
    nome VARCHAR(255) NOT NULL,
    price NUMERIC(15,2) NOT NULL,
    store_id INTEGER NOT NULL,
    inventory_id INTEGER NOT NULL,
    PRIMARY KEY (id)
);

CREATE TABLE inventory (
    id INTEGER NOT NULL PRIMARY KEY,
    amount INTEGER NOT NULL,
    product_id INTEGER NOT NULL
);

接着:

alter table store add constraint fk1 
FOREIGN KEY (store_product) REFERENCES product (id) 
deferrable initially deferred;

alter table product add constraint fk2 
FOREIGN KEY (store_id) REFERENCES store (id);

alter table product add constraint fk3 
FOREIGN KEY (inventory_id) REFERENCES inventory (id);

alter table inventory add constraint fk4 
FOREIGN KEY (product_id) REFERENCES product (id);
2.插入数据

插入相互依赖的数据时,您需要决定首先要在哪个表中插入哪一行。 这就是为什么上面的示例在第一个约束中包含DEFERRABLE INITIALLY DEFERRED的原因。

这样您就可以按顺序插入:

  1. 开始交易。
  2. 插入store - fk1尚未验证。
  3. 插入inventory 验证fk4
  4. 插入product 验证fk2fk3
  5. 提交事务。 此时fk1将最终被验证。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM