2014-07-21 41 views
0

我有一个像SQL这样的表;SQL中的“引用”语句

table Court 
    CourtID numeric(4) primary key 
    Name  varchar(40) not null 
    Place varchar(40) not null 
    Type  varchar(3) not null 
    TypeID numeric(4) references Court(CourtID) default null 

我无法找到有关该参考声明代表什么的信息,以及它如何将TypeID与CourtID相关联?

+0

TYPEID没有在任何其他表使用,所以这就是为什么我认为这不是一个外键,它只是引用了同样的表的主键。但为什么会这样呢? – Sarge

+1

允许外键为自引用 – codenheim

+1

查看DBMS的“CREATE TABLE”语句手册 - 全部解释 –

回答

1

这只是FOREIGN KEY的简写语法。

谷歌搜索结果的种种发现与“SQL引用关键字”

或者只是想它往往能帮助比谷歌搜索(老式的方式)以上。

你的例子显示了一个自引用外键。这是一种常见模式,可以模拟像PARENT或SPOUSE这样的关系,其中所有记录都属于同一个基表,但可以互相引用。

Connected to: 
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production 
With the Partitioning, OLAP, Data Mining and Real Application Testing options 

SQL> create table court(
    2 courtid integer primary key, 
    3 typeid integer references court(courtid) 
    4 ); 

Table created. 

SQL> insert into court values(1,0); 
insert into court values(1,0) 
* 
ERROR at line 1: 
ORA-02291: integrity constraint (MSMITH.SYS_C0016710) violated - parent key not 
found 

SQL> insert into court values(1,1); 

1 row created. 

上述语法将为约束生成一个“随机”名称。更好的语法是明确命名约束。请注意,如果使用其他FOREIGN KEY语法重新创建它,会发生什么情况。

SQL> create table court(
    2 courtid integer primary key, 
    3 typeid integer, 
    4 constraint fk_typeid foreign key (typeid) references court(courtid) 
    5 ); 

Table created. 

SQL> insert into court values(1,0); 
insert into court values(1,0) 
* 
ERROR at line 1: 
ORA-02291: integrity constraint (MSMITH.FK_TYPEID) violated - parent key not 
found 

的关键是现在被命名FK_TYPEID而不是SYS_C0016710