[英]creating table having foreign key that reference another table
我正在使用 PGAdminIII 數據庫。
我有一個名為STOCKREGISTER的表,其中包含由三個字段組成的復合主鍵,即stockregisterId、applicationId 和 date 。
我必須創建另一個表STOCK ,它有一個引用 STOCKREGISTER 的字段stockregisterId的外鍵字段。如果我正在嘗試創建STOCK表,則會顯示一條錯誤消息。錯誤消息是“沒有唯一的約束匹配鍵引用表STOCKREGISTER”。下一步我必須采取什么
第一張桌子
CREATE TABLE stock_register
(
stock_register_id bigint NOT NULL,
application_id bigserial NOT NULL,
production_date date NOT NULL,
opening_bal bigint DEFAULT 0,
quantity_produced bigint,
total_quantity bigint
CONSTRAINT primarykey PRIMARY KEY (stock_register_id, application_id, production_date),
CONSTRAINT "foreignKey" FOREIGN KEY (application_id)
REFERENCES application (application_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
下面是第二張表。這里我不能將stock_register_id作為外鍵
CREATE TABLE Stock
(
stock_id bigint NOT NULL,
stock_register_id bigint,
dimension bigserial NOT NULL,
CONSTRAINT "stockid" PRIMARY KEY (stock_id)
)
我想語法應該是:
CREATE TABLE Stock
(
stock_id bigint NOT NULL,
stock_register_id bigint,
dimension bigserial NOT NULL,
CONSTRAINT "stockid"
FOREIGN KEY (stock_id)
REFERENCES stock_register (stock_register_id)
)
CREATE TABLE Stock
(
stock_id bigint NOT NULL,
stock_register_id bigint,
dimension bigserial NOT NULL,
CONSTRAINT primaryKey PRIMARY KEY (stock_id),
CONSTRAINT foreignKey FOREIGN KEY(stock_register_id)
REFERENCES stock_register (stock_register_id)
)
那應該是你需要的一切。 在使用外鍵時,您還必須確保數據庫表引擎、排序規則和字符集匹配。
對於唯一約束問題,似乎沒有要與你的問題stock_register_id
在PK stock_register
表。 基於錯誤消息,我懷疑這是沒有找到表名STOCKREGISTER stock_register
在你的第二個創建語句。
什么是外鍵? 指向另一個表中特定記錄的指針。
如何根據您的 DDL 識別 stock_register 中的特定記錄? 通過 (stock_register_id, application_id, production_date) 的唯一組合。
因此,只要 application_id 和 production_date 不同,stock_register_id = 1 就可以出現在一千個不同的記錄中。
因此,如果您只有一個 stock_register_id,則無法知道它指向哪個 stock_register 記錄,因此 DBMS 無法強制執行外鍵。
您必須將 application_id 和 production_date 添加到 stock 表,並使所有三列一起成為 stock_register 上復合鍵的 FK,或者您必須從 stock_register 上的 PK 中刪除 application_id 和 production_date,以便 FK 和 PK 列匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.