1
我正在查詢數據庫以查找以下內容。MySQL - 查詢出了什麼問題?
如果客戶在日期A和B之間搜索城市中的酒店,則在兩個日期之間查找並返回房間空閒的酒店。
每種房型都會有不止一個房間(即5個房間爲A型,10個房間爲B型等),我們必須查詢數據庫才能找到那些至少有一個房間至少有一種房型免費。
這是我的表結構:
**Structure for table 'reservations'**
reservation_id
hotel_id
room_id
customer_id
payment_id
no_of_rooms
check_in_date
check_out_date
reservation_date
**Structure for table 'hotels'**
hotel_id
hotel_name
hotel_description
hotel_address
hotel_location
hotel_country
hotel_city
hotel_type
hotel_stars
hotel_image
hotel_deleted
**Structure for table 'rooms'**
room_id
hotel_id
room_name
max_persons
total_rooms
room_price
room_image
agent_commision
room_facilities
service_tax
vat
city_tax
room_description
room_deleted
這是我的查詢:
$city_search = '15';
$check_in_date = '29-03-2010';
$check_out_date = '31-03-2010';
$dateFormat_check_in = "DATE_FORMAT('$reservations.check_in_date','%d-%m-%Y')";
$dateFormat_check_out = "DATE_FORMAT('$reservations.check_out_date','%d-%m-%Y')";
$dateCheck = "$dateFormat_check_in >= '$check_in_date' AND $dateFormat_check_out <= '$check_out_date'";
$query = "SELECT $rooms.room_id,
$rooms.room_name,
$rooms.max_persons,
$rooms.room_price,
$hotels.hotel_id,
$hotels.hotel_name,
$hotels.hotel_stars,
$hotels.hotel_type
FROM $hotels,$rooms,$reservations
WHERE $hotels.hotel_city = '$city_search'
AND $hotels.hotel_id = $rooms.hotel_id
AND $hotels.hotel_deleted = '0'
AND $rooms.room_deleted = '0'
AND $rooms.total_rooms - (SELECT SUM($reservations.no_of_rooms) as tot
FROM $reservations
WHERE $dateCheck
GROUP BY $reservations.room_id) > '0'";
客房每家酒店的每個客房已經預訂的數量將被存儲在保留表。
事情是查詢不會返回任何結果。即使它應該如果我手動計算它。
我試着單獨運行子查詢,我沒有得到任何結果。而且我已經失去了相當數量的頭髮,試圖從昨天開始解決這個查詢。這有什麼問題?還是有更好的方法來做我上面提到的?
編輯:代碼編輯刪除錯誤。感謝Mark Byers。
Sample Data in reservation table
1 1 1 2 1 3 2010-03-29 2010-03-31 2010-03-17
2 1 2 3 3 8 2010-03-29 2010-03-31 2010-03-18
5 1 1 5 5 4 2010-03-29 2010-03-31 2010-03-12
子查詢應返回
Room ID : 1 Rooms Booked : 7
Room ID : 2 Rooms Booked : 8
But it does not return any value at all.... If i remove the dateCheck condition it returns
Room ID : 2 Rooms Booked : 8
謝謝...的錯誤消失......但查詢本身沒有返回任何結果..即使它應該......我不能」唔知道我的生活...我想知道是否有人可以指出我邏輯上出錯的地方.. – SpikETidE 2010-03-18 07:06:17
我懷疑你的子查詢仍然是錯誤的。 GROUP BY看起來很可疑,你可能是指與WHERE相關的子查詢。加入子查詢可能會更好,而不是使用相關的子查詢。然後你確實想要返回這個id。 – 2010-03-18 07:10:12
爲什麼你在查詢中的房間和預訂之間沒有明顯的關係?我強烈建議您使用新的ANSI「JOIN ... ON ...」語法重寫此查詢。 – 2010-03-18 07:11:37