如何在定义列的同一行中定义外键?

Lon*_*ner 2 sql oracle syntax foreign-keys oracle12c

我正在学习使用Oracle 12.1.

下面的外键定义有什么问题?

set echo on
drop table city;
drop table emp;

create table city (
    id number primary key,
    name varchar2(20)
);

create table emp (
    id number,
    cityid number foreign key references city(id)
);
Run Code Online (Sandbox Code Playgroud)

当我执行它时,我收到以下错误.

$ sqlplus / as sysdba @foo.sql
...
...
SQL>
SQL> create table city (
  2      id number primary key,
  3      name varchar2(20)
  4  );

Table created.

SQL>
SQL> create table emp (
  2      id number,
  3      cityid number foreign key references city(id)
  4  );
    cityid number foreign key references city(id)
                  *
ERROR at line 3:
ORA-00907: missing right parenthesis
Run Code Online (Sandbox Code Playgroud)

我认为为定义列的同一行中的列定义外键约束是有效的.

我正在使用http://www.w3schools.com/sql/sql_foreignkey.asp上定义的语法> CREATE TABLE> SQL Server/Oracle/MS Access上的SQL FOREIGN KEY约束.

这种语法在Oracle 12.1中是否真的无效?

Ale*_*sej 6

Oracle中,在定义列时创建约束的语法不允许使用foreign key关键字; 你的陈述应该是:

create table emp (
    id number,
    cityid number references city(id)
);
Run Code Online (Sandbox Code Playgroud)

如果要为约束命名,而不使用单独的语句创建约束,则可以使用:

create table emp (
    id number,
    cityid number constraint CONSTRAINT_NAME references city(id)
);
Run Code Online (Sandbox Code Playgroud)