简体   繁体   中英

Select MySQL rows where a certain month is between two date fields

I have a page which displays events by each month. Each event has a start_date and finish_date as yymmdd. If an event spans over two different months it should show in each month it spans over. For example, if I have an event with a start date of 03/19/2014 and a finish date of 06/19/2014 it should appear in the months of March, April, May and June.

I've been trying to do this in wordpress with meta_query but I just don't think it's possible:

        // Get chosen month to display from URL
$events_month = sanitize_text_field($_GET["month"]);
$events_year = sanitize_text_field($_GET["year"]);

// Convert chosen month to display to a timestamp
$ts = strtotime("$events_month $events_year");

// Create chosen month start end end dates to use for query
$month_start_date = date('Ym01', $ts);
$month_end_date = date('Ymt', $ts);

$args = array(
    'post_type' => 'events',
    'posts_per_page' => 50,
    'order' => 'ASC',
    'orderby' => 'meta_value_num',
    'meta_key' => 'start_date',
    'meta_query'        => array(
        array(
            'key' => 'start_date',
            'value' => array($month_start_date, $month_end_date),
            'type' => 'numeric',
            'compare' => 'BETWEEN'
        )
    )
);

$events = new WP_Query($args);

So'm I'm looking for a pure MySQL solution. Any help please?

I can't tell you much about WP meta queries , but this WHERE clause in SQL should cover all four types of event durations:
Events that happen

  • start in the current month,
  • end in the current month,
  • only in the current month (implies previous conditions),
  • span over the whole current month

Query:

SELECT ... FROM ... WHERE
    start_date BETWEEN month_start AND month_end
    OR end_date BETWEEN month_start AND month_end
    OR month_start BETWEEN start_date AND end_date


EDIT :
Actually, a much easier solution is to select events that

  • start before the current month or within it
  • AND end within this month or after it

Query;

 SELECT ... FROM ... WHERE WHERE start_date <= month_end AND end_date >= month_start 

Without knowledge of meta query stuff (my reference was this ), what you want should work like this:

 'meta_query' => array( 'relation' => 'AND', // default is AND array( 'key' => 'start_date', 'value' => $month_end_date, 'type' => 'numeric', 'compare' => '<=' ), array( 'key' => 'end_date', 'value' => $month_start_date, 'type' => 'numeric', 'compare' => '>=' ) ), 

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