Reputation: 436
I'm really struggling to logically think of things with date ranges.
For example:
If Event A is the 9th - 15th and then the user searches 10th - 13th then at the moment I’ve got it returning all the events that start from the 10th until the 13th as that is what the user searched.
But because Event A is from the 9th - 15th it won't show on that search but I would like it to show because it's still within the range of the 9th - 15th.
I hope that makes sense.
Any help is appreciated.
Upvotes: 0
Views: 85
Reputation: 379
SELECT *
FROM `events` as e
WHERE ( e.date_start BETWEEN [INPUT datestart] AND [INPUT dateend]
OR e.date_end BETWEEN [INPUT datestart] AND [INPUT dateend]
)
;
This will show up possible overlap of dates.
Upvotes: 1
Reputation: 1269493
The logic for overlaps is that two time spans overlap when both begin before the other ends.
This is easy to implement as:
select e.*
from e
where e.start_date < $end_date and
$start_date < e.end_date;
If the end_date
is included in the range, then use <=
instead.
Upvotes: 1
Reputation: 1108
wpquery in an array :
'meta_query' => array(
array(
'key' => $metaKey,
// value should be array of (lower, higher) with BETWEEN
'value' => array('START_DATE', 'END_DATE'),
'compare' => 'BETWEEN',
'type' => 'DATE'
),
)
here is a real world example in mysql and php:
$db = getDB();
$sql = "SELECT
DATE(invoice_date) AS invoice_date,
COUNT(sage_allsalesbyproduct.id) AS row_count,
SUM(sage_allsalesbyproduct.qty) AS total_qty,
SUM(sage_allsalesbyproduct.gross) AS total_gross,
sage_allsalesbyproduct.productcode,
ItemGroup as item_group
FROM sage_allsalesbyproduct
left join stock s on s.ProductCode = sage_allsalesbyproduct.productcode
WHERE
invoice_date BETWEEN :fromdate AND :todate
GROUP BY productcode
order by total_qty desc";
$stmt = $db->prepare($sql);
$stmt->bindParam("fromdate", $fromdate, PDO::PARAM_STR);
$stmt->bindParam("todate", $todate, PDO::PARAM_STR);
$stmt->execute();
$feedData = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($feedData);
remember MySQL uses yyyy-mm-dd format for storing a date value. This format is fixed and it is not possible to change it.
With mysql you can also do something like
SELECT *
FROM order_details
WHERE order_date >= CAST('2014-02-01' AS DATE)
AND order_date <= CAST('2014-02-28' AS DATE);
Upvotes: 0
Reputation: 11
I have a similar table and usually do something like the following to get all the results:
SELECT *
FROM `events`
WHERE ('2019-07-10' BETWEEN `start_date` AND `end_date`
OR '2019-07-13' BETWEEN `start_date` AND `end_date`);
Upvotes: 1