簡體   English   中英

SQL中的“引用”語句

[英]“references” statement in 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相關聯的信息?

它只是FOREIGN KEY的簡寫語法。

各種Google搜索結果都可以通過“ sql reference keyword”找到

或者簡單地嘗試它通常比Google搜索(老式的方法)更有用。

您的示例顯示了一個自引用外鍵。 這是一種常見的模式,可為諸如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

暫無
暫無

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

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