Foreign Key Creation issue in Oracle

依然范特西╮ 提交于 2019-11-27 16:21:23

When you add FK, you are linking a column as a child from the table you are creating, to its parent from the parent table. Hence, you need to provide the child column name, as well as the parent column name.

The general syntax is

CREATE TABLE table_name
(
  column1 datatype null/not null,
  column2 datatype null/not null,
  ...

  CONSTRAINT fk_column
    FOREIGN KEY (column1, column2, ... column_n)
    REFERENCES parent_table (column1, column2, ... column_n)
);

Notice that the columns between FOREIGN KEY brackets, are from the table you are creating, while the columns betweeN REFERENCES PARENT_TABLE are from the parent table.

You do not have a column called CollectibleNum in yourDiecastItems. Hence, the following works fine by adding such a column:

CREATE TABLE collectibles 
  ( 
     collectiblenum NUMBER(10) NOT NULL, 
     CONSTRAINT collectibles_pk PRIMARY KEY(collectiblenum) 
  ); 

CREATE TABLE diecastitems 
  ( 
     diecastname    VARCHAR2(45) NOT NULL, 
     diecastcopy    NUMBER(2) NOT NULL, 
     diecastscale   VARCHAR2(25), 
     colorscheme    VARCHAR2(25), 
     diecastyear    NUMBER(4), 
     collectiblenum NUMBER(10),   --added column
     CONSTRAINT diecastitem_pk PRIMARY KEY(diecastname, diecastcopy), 
     CONSTRAINT diecastitem_collectible_fk FOREIGN KEY(collectiblenum) 
     REFERENCES collectibles(collectiblenum) 
  ); 

FIDDLE

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!