无法在 oracle sql 上设置外键

can't set a foreign key on oracle sql

这是我的代码:

SQL> CREATE TABLE manufacturer(
  manufacturer_id integer primary key,
  manufacturer_name varchar2(20)
);

Table created.

SQL> CREATE TABLE models(
  model_id integer primary key,
  model_name varchar2(20),
  model_year integer,
  eng_cylinder integer,
  eng_horsepower integer,
  manufacturer_id int foreign key references manufacturer(manufacturer_id)
);

它给了我这个错误:

ERROR at line 1:
ORA-00907: missing right parenthesis

我的代码中的括号有什么问题?这仅在我设置外键时发生。

注意:我正在使用来自 Oracle 数据库 11g 快捷版的 SQL cmd。

我试过在 MySQL 上制作这些表格并且效果很好。

没有“FOREIGN KEY”关键字用于内联约束。所以,像这样:

CREATE TABLE manufacturer (manufacturer_id integer primary key, manufacturer_name varchar2(20));

CREATE TABLE models (model_id integer primary key, 
                     model_name varchar2(20),
                     model_year integer, 
                     eng_cylinder integer, 
                     eng_horsepower integer,
                     manufacturer_id int constraint models_fk1 references manufacturer(manufacturer_id));
               
  

               

对,正如马修所说。


或者,创建外键约束 行外 - 然后你使用语法的 foreign key 部分(参见第 9 行):

SQL> CREATE TABLE models
  2    (model_id integer primary key,
  3     model_name varchar2(20),
  4     model_year integer,
  5     eng_cylinder integer,
  6     eng_horsepower integer,
  7     manufacturer_id int,
  8     --
  9     constraint models_fk1 foreign key (manufacturer_id) references manufacturer(manufacturer_id)
 10    );

Table created.

SQL>

或者,另一种选择 - alter table:

SQL> alter table models add constraint models_fk1 foreign key
  2    (manufacturer_id) references manufacturer (manufacturer_id);

Table altered.