我试图获得结果,其中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)
答案 0 :(得分:1)
你的括号已经混淆了。
使用括号将OR
条件与AND
条件分开 - 没有必要将OR
与OR
分开。
请尝试此查询:
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