[英]Mysql find date range
Given the following values YYYY-MM-DD 给定以下值YYYY-MM-DD
$start = 2012-03-21
$stop = 2012-07-15
and the following records in the DB, also YYYY-MM-DD 以及数据库中的以下记录,也是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
? 如何选择$start
$stop
范围内的所有记录? This should include all except the last and first row 这应包括除最后一行和第一行以外的所有内容
Attempt below, which gets records 2 - 4 but not 5. 尝试以下,获取记录2-4,但不记录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. 请注意, Start
总是要来之前To
和 Stop
总是有来后From
为出现这种重叠。
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.