【问题标题】:mysql conditional "not_in" based on another value to parse array into query基于另一个值的mysql条件“not_in”将数组解析为查询
【发布时间】:2015-07-31 16:02:31
【问题描述】:

我有以下数组

$exclude = array(1 => array(1,2,3,4), 2 => array(1,2,3,4));

当密钥验证时,我需要排除内部数组中的值。我不确定我应该使用CASE 还是只使用ANDOR

这是我尝试的开始,但我遗漏了一些东西,因为这不能按预期工作。我将查询附加到 WHERE 子句的末尾,所以这是我唯一的部分可以访问。

foreach($exclude as $blogID => $post_ids) {
    $ids = implode(',', $post_ids);

    if($blogID == 1) {
        $where .= " AND table.BLOG_ID = {$blogID} AND table.ID NOT IN ($ids)";
    } else {
        $where .= " OR table.BLOG_ID = {$blogID} AND table.ID NOT IN ($ids)";
    }
}

【问题讨论】:

  • 打印sql查询看看有什么问题
  • MySQL 不太擅长优化像这样的复杂AND/OR 组合。最好为每一对生成一个查询,并将它们与UNION 结合起来。

标签: php mysql arrays case where


【解决方案1】:

如果没有其余的查询来试验,我不确定,但它可能有助于在所有子句周围添加一些括号,以确保所有 AND 和 OR 按预期交互。像这样的:

if ($exclude) {
    $where .= ' AND ('; // Enclose all the ORs in one set of parentheses
    $or = '';
    foreach($exclude as $blogID => $post_ids) {
        $ids = implode(',', $post_ids);
        // Each individual OR part is enclosed in parentheses
        $where .= "$or(table.BLOG_ID = {$blogID} AND table.ID NOT IN ($ids))";
        $or = ' OR ';
    }
    $where .= ")";
}    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 2021-06-27
    • 2015-08-19
    • 2015-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多