如何从两个日期之间堆叠的表中获取所有行?

时间:2014-12-03 11:47:07

标签: php mysql database

我的问题是我如何从一个表中列出两个日期之间的所有行。

这是我的问题:

   $sql = "SELECT cars.brand,cars.model,cars.reg_num,cars.horse_powers,cars.color FROM cars INNER JOIN clients_cars ON cars.id=clients_cars.cars_id WHERE cars.id IN 
        (SELECT DISTINCT clients_cars.cars_id FROM clients_cars WHERE (rent_date between '$d1' AND '$d2') AND (return_date between '$d1' AND '$d2') AND ((return_date > '$d1') OR (rent_date < '$d2')))"; 

这是有效的,但它只是我希望的一半。

这是我的表:

enter image description here

我想拍摄所有在两个日期之间租用的汽车,即使其中一个日期与其他日期相互叠加而另一个日期与其他日期不同。

例如我添加2014-12-04和2014-12-13,它只显示id为5的汽车。它应该显示id = 8的车,因为它已经在2014-12-02租用并将在2014-12-06返回并且应该向我显示id = 2的车,因为该车将从2014-12-租用10,他正在寻找车到2014-12-13 ...

我希望你能理解我。我需要一些帮助pls :)

2 个答案:

答案 0 :(得分:0)

试试这个sql:

      $sql = "SELECT cars.brand,cars.model,cars.reg_num,cars.horse_powers,cars.color FROM cars LEFT JOIN clients_cars ON cars.id=clients_cars.cars_id  
WHERE (rent_date between '$d1' AND '$d2') OR (return_date between '$d1' AND '$d2')";

答案 1 :(得分:0)

尝试使用此查询

"SELECT DISTINCT cars.id,cars.* FROM cars INNER JOIN clients_cars ON cars.id=clients_cars.cars_id WHERE 
    (clients_cars.rent_date between '$d1' AND '$d2') OR (clients_cars.return_date between '$d1' AND '$d2')";