带有FOREIGN KEY错误的ORACLE CREATE TABLE

时间:2019-12-09 20:20:48

标签: sql oracle foreign-keys create-table

我是Oracle的初学者,在创建带有外键的表时遇到了问题,我也创建了父表region,并且收到了相同的错误。我对W3school进行了研究,并使用了相同的语法,但仍然没有帮助。

CREATE TABLE region(
    region_id INTEGER NOT NULL PRIMARY KEY,
    region_name VARCHAR2(20)
);
CREATE TABLE warehouse(
    warehouse_id INTEGER NOT NULL PRIMARY KEY,
    warehouse_address VARCHAR2(20),
    warehouse_postcode VARCHAR2(8),
    warehouse_phonenm INTEGER,
    region_id FOREIGN KEY REFERENCES region(region_id)
);

3 个答案:

答案 0 :(得分:1)

如果要内联声明外键约束,请忽略“ FOREIGN KEY”。

CREATE TABLE warehouse(
warehouse_id INTEGER NOT NULL PRIMARY KEY,
warehouse_address VARCHAR2(20),
warehouse_postcode VARCHAR2(8),
warehouse_phonenm INTEGER,
region_id REFERENCES region(region_id));

答案 1 :(得分:0)

您需要声明列region_id,然后在其上施加外键约束:

CREATE TABLE warehouse(
    warehouse_id INTEGER NOT NULL PRIMARY KEY,
    warehouse_address VARCHAR2(20),
    warehouse_postcode VARCHAR2(8),
    warehouse_phonenm INTEGER,
    region_id INTEGER,
    constraint warehouse_region_id_fk FOREIGN KEY (region_id) REFERENCES region(region_id)
);

或者您可以使用短路语法(也称为内联约束语法)(在这种情况下,Oracle将为该约束分配一个默认名称):

CREATE TABLE warehouse(
    warehouse_id INTEGER NOT NULL PRIMARY KEY,
    warehouse_address VARCHAR2(20),
    warehouse_postcode VARCHAR2(8),
    warehouse_phonenm INTEGER,
    region_id integer REFERENCES region(region_id)
);

答案 2 :(得分:0)

有几种可能性。

首先是主表:

SQL> CREATE TABLE region(
  2  region_id INTEGER NOT NULL PRIMARY KEY,
  3  region_name VARCHAR2(20)
  4  );

Table created.

SQL>

内联约束(与列在同一行):

SQL> CREATE TABLE warehouse(
  2  warehouse_id INTEGER NOT NULL PRIMARY KEY,
  3  warehouse_address VARCHAR2(20),
  4  warehouse_postcode VARCHAR2(8),
  5  warehouse_phonenm INTEGER,
  6  region_id INTEGER constraint fk_wr REFERENCES region(region_id));

Table created.

SQL>

轮廓约束(在create table的末尾):

SQL> CREATE TABLE warehouse(
  2  warehouse_id INTEGER NOT NULL PRIMARY KEY,
  3  warehouse_address VARCHAR2(20),
  4  warehouse_postcode VARCHAR2(8),
  5  warehouse_phonenm INTEGER,
  6  region_id INTEGER,
  7  --
  8  constraint fk_wr foreign key (region_id) references region (region_id));

Table created.

SQL>

使用alter table

SQL> CREATE TABLE warehouse(
  2  warehouse_id INTEGER NOT NULL PRIMARY KEY,
  3  warehouse_address VARCHAR2(20),
  4  warehouse_postcode VARCHAR2(8),
  5  warehouse_phonenm INTEGER,
  6  region_id INTEGER);

Table created.

SQL> alter table warehouse add constraint fk_wr foreign key (region_id)
  2  references region (region_id);

Table altered.

SQL>