Oracle Sql:外键也是主键语法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13576553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Oracle Sql: foreign-key is also primary key syntax
提问by user1682055
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:
如您所见,我尝试将 an_id 用作 d_cats 中的主键,但也参考 d_animals 表中的 an_id。我收到 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.
另外,我不想为 d_cats 创建另一列。我的教授希望我们只用 an_id 和 feline_leukemia_test_Date 编写 d_cats。谢谢。
回答by turbanoff
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
);
回答by Jeffrey Kemp
Use a named constraint, i.e.:
使用命名约束,即:
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)
);
回答by juergen d
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)
);
回答by Anil
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.
如果您需要使用与 d_animals 表相同的列作为主键和外键,那么您可以使用以下语句。
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)
);