SQL,根据其他 Table 中的相关字段删除记录

SQL, Delete Records Based On Related Fields In Other Table

我有 SQL table 基于酒店数据。我有两个 table 和一个桥 table 来关联它们。我仍在学习中,所以我确信其中一些并不理想或存在潜在风险。

嘉宾Table

CREATE TABLE Guest 
(
    Guest_ID INT PRIMARY KEY IDENTITY (1, 1),
    GuestName NVARCHAR(60) NOT NULL,
    Street NVARCHAR(50) NOT NULL,
    City NCHAR(30) NOT NULL,
    [State] CHAR(2) NOT NULL,

    CONSTRAINT [State.State] 
        FOREIGN KEY ([State]) REFERENCES [State]([State]),
    Zip CHAR(5) NOT NULL,
    Phone VARCHAR(15) NOT NULL
);

房间Table

CREATE TABLE Room 
(
    Room_ID SMALLINT PRIMARY KEY,
    Room_Type_ID SMALLINT NOT NULL,
    CONSTRAINT Room_Type_ID  
        FOREIGN KEY (Room_Type_ID) REFERENCES Room_Type([Type_ID]),
    Amenity_Type_ID SMALLINT NOT NULL,
    CONSTRAINT Amenity_Type_ID 
        FOREIGN KEY (Amenity_Type_ID) REFERENCES Amenity_Type([Type_ID])
);

桥Table(预订)

CREATE TABLE Guest_Bridge_Rooms 
(
    Guest_ID INT NOT NULL,
    CONSTRAINT Guest_ID 
        FOREIGN KEY (Guest_ID) REFERENCES Guest(Guest_ID),
    Room_ID SMALLINT NOT NULL,
    CONSTRAINT Room_ID 
        FOREIGN KEY (Room_ID) REFERENCES Room(Room_ID),
    Date_Start DATE NOT NULL,
    Date_End DATE NOT NULL,
    Occ_Adults SMALLINT NOT NULL,
    Occ_Children SMALLINT NOT NULL,
    Price_Total DECIMAL(13,2) NOT NULL
);

现在有了这些 table,我想编写一个脚本来删除预订(桥接 table)具有特定客人姓名的所有行,方法是通过某种方式关联给定 Guest_ID 到相关 table 中的 GuestName。我可以简单地使用 Guest_ID 但这不是这里的目标。

例如

DELETE FROM Guest_Bridge_Rooms 
WHERE Guest[ID].GuestName = 'John Doe';

有没有简单的方法可以做到这一点?

您可以使用子查询:

DELETE FROM Guest_Bridge_Rooms
    WHERE Guest_ID = (SELECT g.Guest_Id FROM Guests g WHERE g.GuestName = 'John Doe');

注意:确切的语法可能因数据库而异。这也假设 GuestNameGuests 中是唯一的。