oracle—为引用sql plus中不同表的多个主键的外键添加约束?

nom7f22z  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(399)

我是一个初学者学习sql和有困难实现这个概念。
假设您创建以下三个表:

CREATE TABLE dogOwner(
 ownerNo VARCHAR(8) CONSTRAINT ownerNo_pk1 PRIMARY KEY,
 ownerName VARCHAR(10)
);

CREATE TABLE catOwner(
 ownerNo VARCHAR(8) CONSTRAINT ownerNo_pk2 PRIMARY KEY,
 ownerName VARCHAR(10)
);

CREATE TABLE petsAdopted(
 petNo VARCHAR(8) CONSTRAINT petNo_pk PRIMARY KEY,
 ownerNo VARCHAR(8) CONSTRAINT ownerNo_fk1 REFERENCES dogOwner(ownerNo)
                    CONSTRAINT ownerNo_fk2 REFERENCES catOwner(ownerNo)
);

如何正确地为引用其他两个表中的ownerno的外键创建约束?

piok6c0g

piok6c0g1#

你不能。在petsadopted中可以有两列:dogownerno和catownerno以及两个外键。但是table的设计似乎没有意义:不管是谁养的,宠物肯定不是狗就是猫(或者别的什么东西)?
这是另一种设计:

CREATE TABLE owner(
 ownerNo VARCHAR(8) CONSTRAINT ownerNo_pk2 PRIMARY KEY,
 ownerName VARCHAR(10)
);

CREATE TABLE petsAdopted(
 petNo VARCHAR(8) CONSTRAINT petNo_pk PRIMARY KEY,
 petType VARCHAR2(10) NOT NULL CONSTRAINT petTypeChk (CHECK petType in ('CAT','DOG'))
 ownerNo VARCHAR(8) CONSTRAINT ownerNo_fk REFERENCES owner(ownerNo)
);
jq6vz3qz

jq6vz3qz2#

这只是解决你的答案语法部分,你有很多语法错误,但这不会工作,请重新考虑你的设计。

CREATE TABLE dogOwner(
 ownerNo VARCHAR(8) CONSTRAINT ownerNo_pk1 PRIMARY KEY,
 ownerName VARCHAR(10)
);

CREATE TABLE catOwner(
 ownerNo VARCHAR(8),
 ownerName VARCHAR(10),
 CONSTRAINT ownerNo_pk2 PRIMARY KEY (ownerNo),
 CONSTRAINT ownerNo_fk1  FOREIGN KEY (ownerNo) REFERENCES dogOwner(ownerNo)
);

CREATE TABLE petsAdopted(
 petNo VARCHAR(8) ,
 ownerNo VARCHAR(8),
CONSTRAINT petNo_pk PRIMARY KEY (petNo),
CONSTRAINT ownerNo_fk_pet1 FOREIGN KEY (ownerNo) REFERENCES dogOwner(ownerNo),
CONSTRAINT ownerNo_fk_pet2  FOREIGN KEY (ownerNo) REFERENCES catOwner(ownerNo)
);

相关问题