简体   繁体   中英

Mysql find date range

Given the following values YYYY-MM-DD

$start = 2012-03-21
$stop = 2012-07-15

and the following records in the DB, also YYYY-MM-DD

    DATE_FROM    DATE_TO       PRICE
    2012-01-01   2012-03-01    123
    2012-03-01   2012-04-08    123
    2012-04-09   2012-06-04    456
    2012-06-04   2012-07-02    789
    2012-07-02   2012-07-16    111
    2012-07-17   2012-08-17    222

How can I select all records that fall within the range of $start - $stop ? This should include all except the last and first row

Attempt below, which gets records 2 - 4 but not 5.

    SELECT date_from, date_to, price 
    FROM periods
    WHERE (date(date_from) <= '$start' OR date(date_to) <= '$stop')

You want logic something like this:

date_to >= $start AND date_from <= $stop

If this is what you are looking for:

Start-----Stop
       From-------------------To

           Start-----Stop
       From-------------------To

                      Start-----Stop
       From-------------------To

Notice that Start always has to come before To AND Stop always has to come after From for this overlap to occur.

Let me know if any of my assumptions are off of what you are looking for. But, either way, I always find something like this easier to write down so you can visualize and easily see the greater than/less than situations.

SELECT date_from, date_to, price 
    FROM periods
    WHERE (date_from BETWEEN '$start' AND '$stop') AND (date_to BETWEEN '$start' AND '$stop')

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