简体   繁体   中英

Referencing a non-PK field in Oracle

What is the correct way to reference a non-PK field? I don't understand why this example doesn't work (the field c23).

CREATE TABLE tabla1 (
    c11 CHAR(9) PRIMARY KEY,
    c12 VARCHAR2(10),  
    c13 INTEGER,
    CHECK(c13 <= 100)
);

CREATE TABLE tabla2 (
    c21 CHAR(9) PRIMARY KEY,
    c22 VARCHAR2(10),  
    c23 REFERENCES tabla1(c13)
);

You can't. If you want to create a foreign key constraint, you have to reference a primary or unique key column. Any other column won't work.

For example:

SQL> CREATE TABLE tabla1 (
  2      c11 CHAR(9)      PRIMARY KEY,
  3      c12 VARCHAR2(10),
  4      c13 INTEGER      UNIQUE,
  5      CHECK(c13 <= 100)
  6  );

Table created.

SQL> CREATE TABLE tabla2 (
  2      c21 CHAR(9) PRIMARY KEY  REFERENCES tabla1 (c11),
  3      c22 VARCHAR2(10),
  4      c23 INTEGER              REFERENCES tabla1(c13)
  5  );

Table created.

SQL>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM