2014-08-27 72 views
0

我有以下3個表:房間,預訂和reservationroom我聯接返回0結果

其結構如下:

CREATE TABLE `room` (
    `roomID` int(11) NOT NULL AUTO_INCREMENT, 
    `hotelID` int(11) NOT NULL, 
    `roomtypeID` int(11) NOT NULL, 
    `roomNumber` int(11) NOT NULL, 
    `roomName` varchar(255) NOT NULL, 
    `roomName_en` varchar(255) NOT NULL, 
    `roomDescription` text, 
    `roomDescription_en` text, 
    `roomSorder` int(11) NOT NULL, 
    `roomVisible` tinyint(4) NOT NULL, 
    PRIMARY KEY (`roomID`) 
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8; 


CREATE TABLE `reservation` (
    `reservationID` int(11) NOT NULL AUTO_INCREMENT, 
    `customerID` int(11) NOT NULL, 
    `hotelID` int(11) NOT NULL, 
    `reservationCreatedOn` datetime NOT NULL, 
    `reservationCreatedFromIp` varchar(255) CHARACTER SET greek NOT NULL, 
    `reservationNumberOfAdults` tinyint(4) NOT NULL, 
    `reservationNumberOfChildrens` tinyint(4) NOT NULL, 
    `reservationArrivalDate` date NOT NULL, 
    `reservationDepartureDate` date NOT NULL, 
    `reservationCustomerComment` text CHARACTER SET greek, 
    PRIMARY KEY (`reservationID`) 
) ENGINE=InnoDB AUTO_INCREMENT=46 DEFAULT CHARSET=utf8; 

CREATE TABLE `reservationroom` (
    `reservationroomID` int(11) NOT NULL AUTO_INCREMENT, 
    `reservationID` int(11) NOT NULL, 
    `hotelID` int(11) NOT NULL, 
    `roomID` int(11) NOT NULL, 
    PRIMARY KEY (`reservationroomID`) 
) ENGINE=InnoDB AUTO_INCREMENT=46 DEFAULT CHARSET=utf8; 

(請注意,外鍵已被刪除從創建報表簡單起見)

我所試圖做的事:我想所有的客房,未針對特定日期保留,即只能從特定的酒店(我有它的ID)

的免費客房

這裏是我現在所擁有的查詢:

SELECT r.* FROM room r 
LEFT JOIN `reservationroom` rr 
ON r.`hotelID` = rr.`hotelID` 
AND r.`roomID` = rr.`roomID` 
LEFT JOIN `reservation` re 
ON rr.`reservationID` = re.`reservationID` 
WHERE (rr.`reservationroomID` = '' 
    OR rr.`reservationroomID` IS NULL 
    AND re.`reservationArrivalDate` >= 2014-08-27 
    AND re.`reservationDepartureDate` <= 2014-08-29 
    AND r.`hotelID` = 10 
    AND r.`roomVisible` = 1); 

此查詢現在返回0的結果。它應該返回9條記錄,因爲ID = 10的酒店有9個房間是免費的(預訂表中沒有特定日期的預訂)

任何人都可以幫我一下嗎?我試圖在幾個小時內解決這個問題,沒有任何成功。

+0

將您在LEFT JOIN中的表的條件移入JOIN條件和WHERE子句之外。按照事實,你有一個「隱含的」INNER JOIN。 – 2014-08-27 12:48:23

回答

0

您使用的是left join,所以除第一張表之外的所有條件都應在on條款中。我想你想要一個更像這樣的查詢:

SELECT r.* 
FROM room r LEFT JOIN 
    `reservationroom` rr 
    ON r.`hotelID` = rr.`hotelID` AND 
     r.`roomID` = rr.`roomID` LEFT JOIN 
    `reservation` re 
     ON rr.`reservationID` = re.`reservationID` AND 
     re.`reservationArrivalDate` >= 2014-08-27 AND 
     re.`reservationDepartureDate` <= 2014-08-29 
WHERE r.`hotelID` = 10 AND r.`roomVisible` = 1 AND re.reservationID is null; 

我不知道比較是什麼與空字符串。這似乎沒有必要爲此目的。

+0

運行此代碼時,我得到錯誤1064,但我無法找到錯誤在哪裏... – user2417624 2014-08-27 12:53:12

+0

我只是測試它,我得到了id 4的房間兩次,我不知道爲什麼但是... – user2417624 2014-08-27 12:56:04

+0

可以你在SQL小提琴中設置了這個?這聽起來像是數據問題。 – 2014-08-27 14:32:22