好的,我真的被卡住了。我有三张表如下:
表合同
contract_id | hotel_id | start | end
---------------------------------------------------
1 356 2012-12-12 2012-12-16
2 258 2012-12-12 2012-12-16
3 211 2012-12-12 2012-12-16
表 hotel_info
hotel_id | hotel_desc
------------------------------
356 description 1
258 description 2
211 description 3
表费率
contract_id | hotel_id | book_date | rate | closed
--------------------------------------------------------------
1 258 2012-12-12 250.00 1
1 258 2012-12-13 250.00 0
1 258 2012-12-14 250.00 1
1 258 2012-12-15 250.00 1
现在我要做的是从用户输入的特定日期范围之间的合同表中检索所有行。如您所见,费率表按每个日期分开。如果与他们相关的费率为0,我不想获得任何行。因此,例如,如果我想获得2012-12-14和2012-12-15之间的日期费率,我会得到一个结果。但如果我搜索2012-12-12到2012-12-14我没有得到结果。我不知道这是不是很混乱,但这是我到目前为止的mysql,这是行不通的:
SELECT r.*, c.* FROM contracts AS c
INNER JOIN hotel_info AS r ON r.hotel_id = c.hotel_id
INNER JOIN rates AS ra ON ra.contract_id = c.contract_id AND ra.closed != 0
WHERE c.start <= '2012-12-12' AND c.end >= '2012-12-16' GROUP BY r.room_name
对此的任何帮助都将非常感激!如果我错过了什么,请告诉我。提前谢谢!
答案 0 :(得分:2)
如果我正确理解这一点,如果合同规定的日期范围内的相关费率记录范围的比率为1,您只想返回数据。我认为使用NOT EXISTS
可能会做什么你想要的。
SELECT r.*, c.* FROM contracts AS c
INNER JOIN hotel_info AS r ON r.hotel_id = c.hotel_id
INNER JOIN rates AS ra ON ra.contract_id = c.contract_id AND ra.closed != 0
WHERE c.start >= '2012-12-12' AND c.end <= '2012-12-16'
AND NOT EXISTS
(
SELECT
1
FROM rates ira
WHERE ira.contract_id = ra.contract_id
AND ira.rate = 0
)
GROUP BY r.room_name