簡體   English   中英

Oracle 復合主鍵/外鍵題

[英]Oracle composite primary key / foreign key question

我在 oracle 的 1 個表中有一個復合主鍵。 我想為第二個表中的一個表條目創建一個外鍵,該表引用第一個表中的復合主鍵。 我收到錯誤 ORA-02256。 關於如何輸入此內容的任何想法?

CREATE TABLE groupspersonx ( 
  personid number, 
  groupid number, 
  CONSTRAINT pk_persongroupid PRIMARY KEY(personid, groupid) 
); 

CREATE TABLE restrictedgroups ( 
  groupid number, 
  name varchar2(50), 
  dateadded date, 
  since date, 
  notes varchar2(1024), 
  CONSTRAINT pk_groupid PRIMARY KEY(groupid), 
  CONSTRAINT fk_persongroup FOREIGN KEY(groupid) REFERENCES groupspersonx(personid, groupid) 
); 

該錯誤是因為 FOREIGN KEY 是一列,但您試圖提供兩列作為父列。 無需綁定到復合鍵,因為受restrictedgroups的組沒有personid列...

你也有向后的關系 - 使用:

CREATE TABLE restrictedgroups ( 
  groupid number, 
  name varchar2(50), 
  dateadded date, 
  since date, 
  notes varchar2(1024), 
  CONSTRAINT pk_groupid PRIMARY KEY(groupid)
);

CREATE TABLE groupspersonx ( 
  personid number, 
  groupid number, 
  CONSTRAINT pk_persongroupid PRIMARY KEY(personid, groupid),
  CONSTRAINT fk_persongroup FOREIGN KEY(groupid) REFERENCES restrictedgroups(groupid) 
); 

我會為personid來自的任何表添加一個外鍵約束。

CREATE TABLE groupspersonx( 
  personid number, groupid number, 
CONSTRAINT pk_persongroupid PRIMARY KEY(personid, groupid));

CREATE TABLE restrictedgroups ( 
  pid number, 
  groupid number,
  name varchar2(50), 
  dateadded date, 
  since date, 
  notes varchar2(1024), 
  CONSTRAINT pk_groupid PRIMARY KEY(groupid), 
  CONSTRAINT fk_persongroup FOREIGN KEY(pid,groupid) REFERENCES groupspersonx(personid, groupid));

*引用列數與外鍵列數相等

每當您想在列上創建復合主鍵或唯一約束時,都不能在另一個表中提供引用。

例如。

sql>create table t1( a number,b number,c number ,primary key(a,b,c));

table created.

sql>create table g1(a number constraint con_fg references t1(a));

ERROR at line 1:
ORA-02270: no matching unique or primary key for this column-list

這里t1是父表,g1是子表。 子表可以在一列中包含重復值。 所以 oracle 將不允許該表的列。

也可以看看

SQL>select constraint_name,constraint_type from user_constraints where table_name='T1';

CONSTRAINT_NAME                C
------------------------------ -
SYS_C005822                    P

因此,這里也是所有三列的唯一約束,即 t1 表中的 a、b、c。

這就是為什么您不能在復合主鍵或復合唯一約束上創建外部

你不能使用:

CONSTRAINT fk_persongroup FOREIGN KEY(groupid) REFERENCES groupspersonx(personid, groupid)

也改變它:

CONSTRAINT fk_persongroup FOREIGN KEY(groupid) REFERENCES groupspersonx(groupid) 

那應該行得通。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM