多个AND,NOT IN条件的组合在php mysql查询

时间:2017-05-10 08:45:37

标签: php mysql sql database

您好,我写了以下查询

SELECT *
FROM `product`
WHERE (`color` IN ('black'))
   OR (`pattern` IN ('pattern-1', 'pattern-2', 'pattern-3'))
  AND `p_category` LIKE '%Blind%'
  AND id NOT IN('20', '19', '18', '17', '11')
ORDER BY id DESC

但出于某种原因,它会显示标识为'20', '19', '18', '17', '11'

的产品

我认为这些信息足以解决这个问题。

更新

在这里,我无法弄清楚我需要改变的地方。我在这里使用ajax。所有操作都在该页面中进行。将变量转到ajax调用页面我执行的操作是

$keyword_array= ( [keyword] => Array ( 
                    [0] => color*black 
                    [1] => pattern*pattern-1
                    [2] => pattern*pattern-2
                    [3] => pattern*pattern-3 ) 
        [y_id] => Array ( 
                    [0] => 20
                    [1] => 19
                    [2] => 18
                    [3] => 17
                    [4] => 11 ) 
       [category] => Romex Blind );


       foreach ( $keyword_array as $value) {
            list($before, $after) = explode('*', $value);
            $elements[$before][] = $after;
        }

        $parts = [];

        foreach ($elements as $column => $values) {
            $parts[] = "(`$column` IN ('" . implode("', '", $values) . "'))";
        }

        $appear=implode("', '", $_POST['y_id']);

        $query = "SELECT * FROM `product` WHERE " . implode(' OR ', $parts). "  AND `p_category` LIKE '%".$_POST['category']."%' AND id NOT IN('{$appear}') ORDER BY id DESC";

请告知此查询中的错误。

2 个答案:

答案 0 :(得分:4)

围绕或表达破解:

SELECT *
FROM `product`
WHERE (`color` IN ('black')
   OR `pattern` IN ('pattern-1', 'pattern-2', 'pattern-3'))
  AND `p_category` LIKE '%Blind%'
  AND id NOT IN('20', '19', '18', '17', '11')
ORDER BY id DESC

<强>更新 尝试

 $query = "SELECT * FROM `product` WHERE (" . implode(' OR ', $parts). ")  AND `p_category``

答案 1 :(得分:-1)

你可以写这样的查询

SELECT * FROM product WHERE (color = 'black' OR pattern IN ('pattern-1', 'pattern-2', 'pattern-3')) AND p_category LIKE '%Blind%' AND id NOT IN (20, 19, 18, 17, 11) ORDER BY id

如果有两个或更多条件,您只能使用OR,只需要一个答案,如

在你的情况下你查询似乎错误的数据将得到