WHERE,LIKE OR AND NOT运算符未返回预期结果

时间:2018-04-15 15:13:55

标签: sql mysqli

我试图获得结果,其中kids列为NULL但由于某种原因,sql返回所有匹配的LIKE OR行,即使kids列不为null,我也尝试了下面的代码。

此SQL按预期返回结果

SELECT `name`, `middlename`, `kids` 
FROM persons 
WHERE (name LIKE '%brenda%' OR middlename LIKE '%smith%') 
   OR (name LIKE '%kent%' OR middlename LIKE '%smith') 
   AND kids IS NOT NULL

这个SQL返回与上面相同的结果,即使kids列包含数据也不为空?

SELECT `name`, `middlename`, `kids` 
FROM persons 
WHERE (name LIKE '%brenda%' OR middlename LIKE '%smith%') 
   OR (name LIKE '%kent%' OR middlename LIKE '%smith%') 
   AND kids IS NULL

我尝试了这个,但即使孩子专栏不是空的,它仍会返回结果

SELECT `name`, `middlename`, `kids` 
FROM persons 
WHERE (name LIKE '%brenda%' OR middlename LIKE '%smith%' AND kids IS NULL) 
   OR (name LIKE '%kent%' OR middlename LIKE '%smith%' AND kids IS NULL)

2 个答案:

答案 0 :(得分:1)

你的括号已经混淆了。 使用括号将OR条件与AND条件分开 - 没有必要将OROR分开。
请尝试此查询:

SELECT `name`, `middlename`, `kids` 
FROM persons 
WHERE (name LIKE '%brenda%' 
    OR name LIKE '%kent%' 
    OR middlename LIKE '%smith') 
AND kids IS NULL

答案 1 :(得分:1)

所有OR条件都需要

括号:

    SELECT 
        `name`, `middlename`, `kids` 
    FROM 
        persons 
    WHERE 
       (name LIKE '%brenda%' OR middlename LIKE '%smith%' 
        OR name LIKE '%kent%' OR middlename LIKE '%smith) 
       AND kids IS NOT NULL