ORA-00907:创建外键Oracle 12c时缺少右括号

时间:2017-12-31 19:58:03

标签: sql oracle foreign-keys sqlplus ddl

我想创建一个包含一个自动生成的主键和两个外键的表,但我遇到此错误...

create table answers
( id number generated by default on null as identity primary key
, question_id number foreign key references questions(id)
, user_id number foreign key references users(id)
, answer varchar(1000)
, post_date date);

create table answers (id number generated by default on null as identity primary key, question_id number foreign key references questions(id), user_id number foreign key references users(id), answer varchar(1000), post_date date)
  

第1行的错误:   ORA-00907:缺少右括号

然后,我尝试了这个:

create table answers
( id number generated by default on null as identity primary key
, question_id number foreign key (question_id) references questions(id)
, user_id number foreign key (user_id) references users(id)
, answer varchar(1000)
, post_date date );

create table answers
( id number generated by default on null as identity primary key
, question_id number foreign key (question_id) references questions(id)
, user_id number foreign key (user_id) references users(id)
, answer varchar(1000)
, post_date date )
                                                                                                     *
  

第1行的错误:   ORA-00907:缺少右括号

它仍然给出了相同的错误!

但是,如果我分两步完成:

create table answers
( id number generated by default on null as identity primary key
, question_id number not null
, user_id number not null
, answer varchar(1000)
, post_date date );

Table created.

alter table answers
add foreign key (question_id) references questions(id) add foreign key (user_id) references users(id);
  

表格改变了。

任何人都可以让我离开这个吗?

2 个答案:

答案 0 :(得分:3)

在作为列定义的一部分内联定义约束时,您不需要说foreign key

create table answers
( id number generated by default on null as identity primary key
, question_id number references questions(id)
, user_id number references users(id)
, answer varchar(1000)
, post_date date);

祝你好运。

答案 1 :(得分:2)

您可以在底部定义外键,与列名称不相邻,如下所示:

create table answers (
                      id number generated by default on null as identity primary key, 
                      question_id number, 
                      user_id number, 
                      answer varchar(1000), 
                      post_date date,
                      foreign key(question_id) references questions(id),
                      foreign key(user_id) references users(id)                            
                     );