2016-03-20 68 views
0

我目前正試圖解決一個問題,但我卡在一個point.Below是從給定。我正在嘗試使用完整性增強功能創建預訂表,但在限制範圍內,同一個房間無法進行雙重預訂。預訂表使用完整性增強

酒店(hotelNo,hotelName,city)房間(roomNo,hotelNo,類型,價格)Booking(hotelNo,guestNo,dateFrom,dateTo,roomNo)Guest(guestNo,guestName,guestAddress)主鍵。房間包含每間酒店的房間詳細信息,並且(房間不,hoteINo)構成主要關鍵。預訂包含預訂的詳細信息,並且(hoteINo,guestNo,dateFrom)構成主鍵。客戶包含客人信息和guestNo是主鍵..

這是多遠我已經:

CREATE TABLE Booking(
    hotelNo  HotelNumbers  NOT NULL, 
    guestNo GuestNumbers  NOT NULL, 
    dateFrom BookingDate  NOT NULL, 
    dateTo  BookingDate  NULL, 
    roomNo  RoomNumber  NOT NULL, 
    PRIMARY KEY (hotelNo, guestNo, dateFrom), 
    FOREIGN KEY (hotelNo) REFERENCES Hotel 
     ON DELETE CASCADE ON UPDATE CASCADE, 
    FOREIGN KEY (guestNo) REFERENCES Guest 
     ON DELETE NO ACTION ON UPDATE CASCADE, 
    FOREIGN KEY (hotelNo, roomNo) REFERENCES Room 
     ON DELETE NO ACTION ON UPDATE CASCADE, 
    CONSTRAINT RoomBooked 
    CHECK (NOT EXISTS (SELECT * 
       FROM Booking b 
       WHERE b.dateTo > Booking.dateFrom AND 
       b.dateFrom < Booking.dateTo AND 
       b.roomNo = Booking.roomNo AND 
       b.hotelNo = Booking.hotelNo)), 
    CONSTRAINT GuestBooked 
    CHECK (NOT EXISTS (...............) 
+0

這甚至讓 - 具有子查詢檢查約束?我知道SQL Server不允許它,不確定MySQL。但是,我建議在應用層保留數據完整性約束,或者如果您希望將其保留在數據庫級別,則通過數據庫觸發器應用它們,以便您可以更好地處理事務和錯誤消息。 – AKS

回答

0

我認爲,你從4個領域需要在預訂PK:hotelNo,guestNo,dateFrom,roomNo ;你必須修改約束RoomBooked這樣的:

CREATE TABLE Booking(
hotelNo  HotelNumbers  NOT NULL, 
guestNo GuestNumbers  NOT NULL, 
dateFrom BookingDate  NOT NULL, 
dateTo  BookingDate  NULL, 
roomNo  RoomNumber  NOT NULL, 
PRIMARY KEY (hotelNo, guestNo, dateFrom, roomNo), 
FOREIGN KEY (hotelNo) REFERENCES Hotel 
    ON DELETE CASCADE ON UPDATE CASCADE, 
FOREIGN KEY (guestNo) REFERENCES Guest 
    ON DELETE NO ACTION ON UPDATE CASCADE, 
FOREIGN KEY (hotelNo, roomNo) REFERENCES Room 
    ON DELETE NO ACTION ON UPDATE CASCADE, 
CONSTRAINT RoomBooked 
CHECK (NOT EXISTS ( 
SELECT 1 
FROM Booking b 
WHERE (
    isnull(b.dateTo, b.dateFrom) 
    between Booking.dateFrom and isnull(Booking.dateTo, Booking.dateFrom) 
    or b.dateFrom 
    between Booking.dateFrom and isnull(Booking.dateTo, Booking.dateFrom)) 
AND b.roomNo = Booking.roomNo 
AND b.hotelNo = Booking.hotelNo))) 

,我認爲,一個客人可以預訂一個以上的房間,所以你不能設置約束的GuestBooked