Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

sql - Foreign Key Creation issue in Oracle

When I try to create these two tables I get:

"SQL Error: ORA-00904: "COLLECTIBLENUM": invalid identifier"

I'm sure it's a noob error but I'm just not seeing it. Can someone please point out what I'm doing wrong? Thanks in advance.

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),  
  CONSTRAINT diecastItem_pk PRIMARY KEY(DiecastName, DiecastCopy),  
  CONSTRAINT diecastItem_Collectible_fk FOREIGN KEY(CollectibleNum) REFERENCES Collectibles(CollectibleNum));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...