0
create table Person(
    SSN INT,
    Name VARCHAR(20),
    primary key(SSN)
);
create table Company(
CompanyID INT,
Name VARCHAR(20)
primary key(SSN)

create table Car(
    PlateNr INT,
    Model VARCHAR(20),
    primary key(PlateNr)
);

create table CarOwner(
    SSN INT,
    PlateNr INT,
    primary key(SSN, PlateNR)
    foreign key(SSN) references Person (SSN),
    foreign key(PlateNr) references Car (PlateNr)
);

create table CompanyWorker(
    SSN INT,
    CompanyID INT
    primary key(SSN, CompanyID),
    foreign key(SSN) references Person (SSN),
    foreign key(CompanyID) references Company (CompanyID)
);

Insert into Person(SSN, Name) VALUES ('123456789','Max');
Insert into Person(SSN, Name) VALUES ('123456787','John');
Insert into Person(SSN, Name) VALUES ('123456788','Tom');

insert into Company(CompanyID, Name) VALUES('1','IKEA');
insert into Company(CompanyID, Name) VALUES('2','Starbucks');

Insert into Car(PlateNr, Model) VALUES ('123ABC','Volvo');
Insert into Car(PlateNr, Model) VALUES ('321CBA','Toyota');
Insert into Car(PlateNr, Model) VALUES ('333AAA','Honda');

Insert into CarOwner(SSN, PlateNr) VALUES ('123456789','123ABC');
Insert into CarOwner(SSN, PlateNr) VALUES ('123456787','333AAA');
Insert into CarOwner(SSN, PlateNr) VALUES ('123456788','321CBA');

insert into CompanyWorker(SSN, CompanyID) VALUES('123456789','1');
insert into CompanyWorker(SSN, CompanyID) VALUES('123456787','1');

这是我的表并插入到这些表中,我遇到的问题是删除一个人。我希望能够从“Person”表中删除一个人,例如

DELETE FROM Person WHERE SSN = '123456789';

但问题是我必须从与该人有关系的所有其他表中删除该人。Person 与 CarOwner 和 CompanyWorker 有关系。当然,我可以一次简单地执行 3 个单独的删除语句:

DELETE FROM Person WHERE SSN = '123456789';
DELETE FROM CarOwner WHERE SSN = '123456789';
DELETE FROM CompanyWorker WHERE SSN = '123456789';

但是,如果 CompanyWorker 中不存在此 SSN,我会遇到问题,因为它试图删除那里不存在的东西。所以我需要在以某种方式删除之前先检查它是否存在,这是我的问题。

4

1 回答 1

1

如果您使用 MSSQL 作为数据库引擎,您可以使用 ALTER TABLE 添加一个 FOREIGN CONSTRAINT with ON DELETE CASCADE

ALTER TABLE CarOwner
    ADD CONSTRAINT FK_CarOwner_SSN 
        FOREIGN KEY (SSN) 
        REFERENCES Person (SSN) 
        ON DELETE CASCADE 
于 2013-10-01T14:01:37.203 回答