简体   繁体   中英

Oracle Sql: foreign-key is also primary key syntax

I just have a quick question about notation. I have two tables right now.

This one has basic animal information:

 create table d_animals (
  an_id     integer     primary key
, an_gender varchar2(1) not null
, an_dob    date        not null
, an_name   varchar2(10)    not null
);

This one is about cats:

 create table d_cats (
       an_id                        integer     primary key
     , feline_leukemia_test_date    date        not null
     , an_id    foreign key references d_animals_(an_id)
     );

As you can see, I'm trying to use an_id as the primary key in d_cats but also refernce the an_id from the d_animals table. I'm getting the following error for d_cats:

 ORA-00957: duplicate column name

So how do I correctly write this?

Also, I don't want to create another column for d_cats. My professor wants us to write d_cats with only an_id and feline_leukemia_test_Date. Thanks.

You can inline foreign key too:

create table d_cats
( an_id                        integer     primary key references d_animals(an_id)
, feline_leukemia_test_date    date        not null
);

Use a named constraint, ie:

create table d_cats (
   an_id                        integer     primary key
 , feline_leukemia_test_date    date        not null
 , constraint d_cats_animals_fk foreign key (an_id) references d_animals (an_id)
 );

Use a different name for the foreign key.

create table d_cats (
       an_id                        integer     primary key
     , feline_leukemia_test_date    date        not null
     , cats_an_id    foreign key references d_animals_(an_id)
     );

If you need to use same column as of d_animals table to be both primary key and foreign key then you can use below statements.

CREATE TABLE d_cats
(
  an_id                      INTEGER PRIMARY KEY,
  feline_leukemia_test_date  DATE NOT NULL,
  CONSTRAINT PK_d_cats_an_id PRIMARY KEY (an_id),
  CONSTRAINT FK_d_cats_an_id FOREIGN KEY (an_id) REFERENCES d_animals(an_id)
);

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