我有下表:
CREATE TABLE Appartment
(
SizeSquareMeter INT,
Type VARCHAR(30) NOT NULL,
StreetName VARCHAR(30) NOT NULL,
Number INT NOT NULL,
Door INT NOT NULL,
CONSTRAINT App_Address PRIMARY KEY(StreetName, Number, Door)
)
我还需要创建下表
CREATE TABLE Resident
(
RID INT PRIMARY KEY NOT NULL,
FirstName VARCHAR(30) NOT NULL,
LastName VARCHAR(30) NOT NULL,
BirthDate DATE NOT NULL,
StreetName VARCHAR(30) NOT NULL,
Number INT NOT NULL,
Door INT NOT NULL,
CONSTRAINT Resident_Address
FOREIGN KEY (StreetName, Number, Door) REFERENCES Appartment(StreetName, Number, Door)
)
现在上面的方法有效,但是它重复了地址,但我不希望这样,有没有办法我可以创建从Resident
到Appartment
的外键,而无需重复地址和无需为 Appartment
创建新的主键?
注意:无论它是否重要,基本上都应该是有效的Microsoft DDL。
答案 0 :(得分:1)
您只能使用特定ID来执行外键。这违反了规范化规则(当您在两个表中使用相同的详细信息时)。基本上,您可以在Appartment表上创建UniqueId。从已经在公寓表中注册的居民表中删除街道名称,号码和门。使用外键将AppartmentId添加到居民。这是更新的创建示例:
CREATE TABLE Appartment(
ApartmentId INT NOT NULL ,
SizeSquareMeter int,
Type varchar(30) NOT NULL,
StreetName varchar(30) NOT NULL,
Number int NOT NULL,
Door int NOT NULL,
CONSTRAINT PK_Appartment PRIMARY KEY(ApartmentId)
)
CREATE TABLE Resident(
RID int PRIMARY KEY NOT NULL,
AppartmentId INT NOT NULL,
FirstName varchar(30) NOT NULL,
LastName varchar(30) NOT NULL,
BirthDate Date NOT NULL,
CONSTRAINT FK_Resident_Address FOREIGN KEY (AppartmentId) REFERENCES Appartment
)
答案 1 :(得分:1)
外键引用可以指向表中的任何唯一键。因此,您可以这样做:
CREATE TABLE Appartment (
AppartmentId int identity unique not null,
SizeSquareMeter INT,
Type VARCHAR(30) NOT NULL,
StreetName VARCHAR(30) NOT NULL,
Number INT NOT NULL,
Door INT NOT NULL,
CONSTRAINT App_Address PRIMARY KEY(StreetName, Number, Door)
);
CREATE TABLE Resident (
RID INT PRIMARY KEY NOT NULL,
FirstName VARCHAR(30) NOT NULL,
LastName VARCHAR(30) NOT NULL,
BirthDate DATE NOT NULL,
AppartmentId int not null,
CONSTRAINT Resident_Address
FOREIGN KEY (AppartmentId) REFERENCES Appartment(AppartmentId)
);
也就是说,我强烈认为您应该更改数据结构,以便公寓表的主键是identity
列。