MySQL根据START和END日期之间的日期显示值

时间:2015-11-17 09:06:59

标签: mysql

我正在尝试制作简单的房屋预订系统,我的数据库就像:

TABLE HOUSES
id | name
============
1  | house_1
2  | house_2

TABLE RESERVATIONS
id | id_house | date_start | date_end
=====================================
1  | 2        | 2015-11-02 | 2015-11-10
2  | 1        | 2015-10-02 | 2015-10-15

我不知道如何根据新预订显示预订房屋,例如。

  

id_house 2 2015-11-05 2015-11-20

系统应该输出:House num。 2 在这一天保留

3 个答案:

答案 0 :(得分:2)

请考虑以下事项:

CREATE TABLE reservations
(id INT NOT NULL
,id_house INT NOT NULL
,date_start DATE
,date_end DATE
);

INSERT INTO reservations VALUES
(1,2,'2015-11-02','2015-11-10'),
(2,1,'2015-10-02','2015-10-15');

SELECT * 
  FROM reservations x 
  LEFT 
  JOIN (SELECT '2015-11-05' my_start,'2015-11-20' my_end) y 
    ON y.my_start < x.date_end 
   AND y.my_end > x.date_start;
+----+----------+------------+------------+------------+------------+
| id | id_house | date_start | date_end   | my_start   | my_end     |
+----+----------+------------+------------+------------+------------+
|  1 |        2 | 2015-11-02 | 2015-11-10 | 2015-11-05 | 2015-11-20 |
|  2 |        1 | 2015-10-02 | 2015-10-15 | NULL       | NULL       |
+----+----------+------------+------------+------------+------------+

答案 1 :(得分:0)

试试这个......

SELECT ho.*,re.* FROM tbl_house AS ho LEFT JOIN tbl_reservation
WHERE now() >= date_start and now() <= date_end

希望这有帮助。

答案 2 :(得分:0)

输入:新预订的日期范围(2015-11-05至2015-11-20)

输出:已为这些日期预留的房屋列表

<强>查询:

SELECT HOUSES.name, HOUSES.id, RESERVATIONS.date_start, RESERVATIONS.date_end
FROM RESERVATIONS
LEFT JOIN HOUSES ON HOUSES.id=RESERVATIONS.id_house 
WHERE
  RESERVATIONS.date_start < '2015-11-20'
  AND
  RESERVATIONS.date_end > '2015-11-20'

类似的东西,但这取决于你的逻辑(我没有完全理解)。

希望有所帮助。