我創建了一個表架構,但我不知道在這種情況下我應該如何運行腳本,因為我對需要創建其他表的每個表都有約束,是否有任何方法可以在創建后添加約束或其他方法在腳本中保持正確的表模式相等?
我使用 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)
);
uj5u.com熱心網友回復:
首先創建沒有外鍵約束的表,然后使用ALTER它來更改外鍵,這將是一種解決方法
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),
);
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)
);
CREATE TABLE IF NOT EXISTS inventory (
id INTEGER NOT NULL PRIMARY KEY,
amount INTEGER NOT NULL,
product_id INTEGER NOT NULL,
);
Alter table store
ADD Constraint fk
FOREIGN KEY (store_product) REFERENCES
product (id);
Alter table inventory
ADD Constraint fk1
FOREIGN KEY (product_id) REFERENCES
product (id);
Alter table product
ADD Constraint fk2
FOREIGN KEY (store_id) REFERENCES store (id),
FOREIGN KEY (inventory_id) REFERENCES
inventory (id);
uj5u.com熱心網友回復:
外鍵約束有兩個問題:
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在第一個約束中。
這樣你就可以按順序插入:
- 開始交易。
- 插入
store--fk1尚未驗證。 - 插入
inventory. 驗證fk4. - 插入
product. 驗證fk2和fk3. - 提交交易。此時
fk1將最終得到驗證。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/376034.html
