【问题标题】:Select MySQL rows where a certain month is between two date fields选择某个月份在两个日期字段之间的 MySQL 行
【发布时间】:2014-03-20 03:06:00
【问题描述】:

我有一个按月显示事件的页面。每个事件都有一个 start_date 和 finish_date 作为 yymmdd。如果一个事件跨越两个不同的月份,它应该在它跨越的每个月显示。例如,如果我的活动开始日期为 2014 年 3 月 19 日,结束日期为 2014 年 6 月 19 日,则它应该出现在 3 月、4 月、5 月和 6 月。

我一直在尝试使用 meta_query 在 wordpress 中执行此操作,但我认为这是不可能的:

        // 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);

所以我正在寻找一个纯 MySQL 解决方案。有什么帮助吗?

【问题讨论】:

    标签: php mysql sql wordpress date


    【解决方案1】:

    关于 WP meta queries 我不能告诉你太多,但是 SQL 中的这个 WHERE 子句应该涵盖所有四种类型的事件持续时间:
    发生的事件

    • 从当月开始,
    • 当月结束,
    • 仅在当前月份(暗示以前的条件),
    • 跨越整个当月

    查询:

    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
    


    编辑:
    实际上,一个更简单的解决方案是选择事件
    • 在当月之前或当月内开始
    • 并在本月内或之后结束

    查询;

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

    没有元查询知识(我的参考是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' => '>='
        )
    ),
    

    【讨论】:

    • 您的代码的问题在于它不会涵盖超过一个月的事件。我需要一个事件来显示它跨越的每个月。谢谢
    • @user3398457 为什么不呢?如果start_date &lt;= month_end &amp;&amp; end_date &gt;= month_start,那么这也将匹配任何之前开始并且之后结束的事件,对吧?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    • 2021-09-14
    • 2017-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多