1

好吧,我真的被困住了。我有三个表如下:

合约

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

对此的任何帮助将不胜感激!如果我遗漏了什么,请告诉我。提前致谢!

4

1 回答 1

2

如果我正确理解这一点,您只想在为合同指定的日期范围内的相关费率记录范围内的费率为 1 时返回数据。我认为 usingNOT 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
于 2012-11-13T04:46:12.687 回答