简体   繁体   English

外键刷新

[英]Foreign Key Refrencing

You will have to forgive me as its been a while since I have created a database. 自从我创建数据库以来,已经有一段时间了,您将不得不原谅我。

I have created the following table; 我已经创建了下表;

CREATE TABLE Counties (
    CountID VARCHAR(10) PRIMARY KEY,
    Countyname CHAR(10)
);

Now I want to create the second one; 现在我要创建第二个。

CREATE TABLE STAFF (
    RepID VARCHAR(10) PRIMARY KEY,
    Surname CHAR(10),
    foreign key (CountID) references Counties(CountID)
);

However I get; 但是我明白了。

CREATE TABLE STAFF (RepID VARCHAR(10) PRIMARY KEY , Surname CHAR(10),
foreign key (CountID) references Counties(CountID)) Error at Command
Line : 1 Column : 84 Error report - SQL Error: ORA-00904: "COUNTID":
invalid identifier
00904. 00000 -  "%s: invalid identifier"
*Cause:    
*Action:

I have searched around and have read it because whatever you are trying to reference doesn't exist. 我搜索并阅读了它,因为您要参考的内容都不存在。

However; 然而;

DESCRIBE COUNTIES;

 Name       Null      Type         
----------  --------  ------------  
COUNTID     NOT NULL  VARCHAR2(10)  
COUNTYNAME            CHAR(10)

You have to specify the field first. 您必须先指定字段。 Now you are creating just the FK on a field that does not exist. 现在,您将在不存在的字段上仅创建FK。 The statement should define the field, and define the foreign key separately: 该语句应定义字段,并分别定义外键:

CREATE TABLE STAFF (
  RepID VARCHAR(10) PRIMARY KEY , 
  Surname CHAR(10), 
  CountID VARCHAR(10),
  foreign key (CountID) references Counties(CountID));

There is a short syntax that lets you combine them. 有一个简短的语法可让您组合它们。 But it is slightly different and it actually adds the FK to the field declaration (thanks to ypercube). 但这稍有不同,它实际上将FK添加到字段声明中(感谢ypercube)。 It still needs the field type, but lets you add a shortened FK declaration after the field declaration: 它仍然需要字段类型,但是允许您在字段声明之后添加一个缩短的FK声明:

CREATE TABLE STAFF (
  RepID VARCHAR(10) PRIMARY KEY , 
  Surname CHAR(10), 
  CountID VARCHAR(10) references Counties(CountID));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM