简体   繁体   中英

MySQL query with date ranges

I have a table with the following records:

    id_hotel - fecha_desde - fecha_hasta
-------------------------------------------------- ----
       4        2011-01-01    2011-01-14
       4        2011-01-05    2011-01-30
       4        2011-01-31    2011-02-07
       4        2011-02-13    2011-02-25
       3        2011-01-01    2011-03-14
       5        2011-01-01    2011-01-29
       5        2011-01-30    2011-02-27

And I need to make this query:

I have the date $desde = 2011-01-04 and $hasta = 2011-03-02

The result I have to give is the id_hotel have availability at this time and in between does not find any empty day (example: id_hotel 4) that between 02/07/2011 and 13/02/2011 are 6 days that not available.

Whereupon the id_hotel = 4 would not have to leave, but the 3 and 5.

With the example of id_hotel = 3 , I have no problem as I use the following query:

SELECT       id_hotel
FROM         fechas_disponibilidad
WHERE        \''. $desde. '\' BETWEEN    fecha_desde     AND    fecha_hasta
AND          \''. $hasta.  '\' BETWEEN    fecha_desde     AND    fecha_hasta

I have the date from: 2011-01-04 and date up to: 03/02/2011

The result I have to give is the id_hotel have availability at this time and in between does not find any empty day (example: id_hotel 4) that between 02/07/2011 and13/02/2011 are 6 days that not available.

Whereupon the id_hotel = 4 would not have to leave, but the 3 and 5.

With the example of id_hotel = 3 , I have no problem as I use the following query:

But when I have more than one date range id_hotel column, do not know how to realize the query.

I don't think it can be done in one query. I suggest following algorithm (written in pseudo-SQL, substitute real db operations for my select() function):

$results = array();
$hotels = select("SELECT DISTINCT id_hotel FROM fechas_disponibilidad WHERE '" . $desde . "' BETWEEN fecha_desde AND fecha_hasta")
foreach ($hotels as $hotel_id) {
    $available_to = $desde;
    while ($available_to < $hasta) {
        $available_to = select("SELECT MAX(fecha_hasta) FROM fechas_disponibilidad WHERE id_hotel = " . $hotel_id . " AND '" . $availableTo . "' BETWEEN (fecha_desde - 1) AND fecha_hasta ");
        if (isNull($available_to)) {
            continue 2;
        }
    }
    $results[] = $hotel_id;
}

Or create MySQL function which does the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM