我正在按照所选值执行过滤器,这是我的数据库的样子:
contactgroup media gender age isdelete married children driverslicens restatus retype
-----------------------------------------------------------
contactgroup1 SMS Male 28 0 yes yes yes owner apart
contactgroup1 SMS Female 26 0 no null no rent house
contactgroup2 SMS Male 32 0 null no null owner null
contactgroup2 SMS Male 38 0 yes yes no null null
这是我的疑问:
SELECT * FROM contact
where isdeleted = 0
AND contactgroup in ('Contactgroup1', '')
and media = 'sms'
AND (`gender` = 'female' OR `gender` = 'male' OR `gender` is null)
AND (`married` = 'yes' OR `married` = 'no' OR `married` is null)
AND (`children` = 'yes' OR `children` = 'no' OR `children` is null)
AND (`driverslicense` = 'yes' OR `driverslicense` = 'no' OR `driverslicense` is null)
AND (`retype` = 'owner' OR `retype` = 'renting' OR `retype` is null)
AND (`restatus` = 'apart' OR `restatus` = 'house' OR `restatus` is null)
and age BETWEEN 18 AND 60
此查询应显示有关contactgroup1
的数据,但是它显示了所有四个数据,任何人都可以告诉我为什么它显示我出错的所有数据?
答案 0 :(得分:3)
您需要整理查询和分组OR条件
SELECT
*
FROM
contact
WHERE isdeleted = 0
AND contactgroup IN ('Contactgroup1', '')
AND media = 'sms'
AND (
`gender` = 'female'
OR `gender` = 'male'
OR `gender` = 'null'
)
AND age BETWEEN 18
AND 60
使用新列
更新问题您需要使用IS NULL
SELECT
*
FROM
contact
WHERE isdelete = 0
AND contactgroup IN ('Contactgroup1', '')
AND media = 'sms'
AND (
`gender` = 'female'
OR `gender` = 'male'
OR `gender` = 'null'
)
AND (
`married` = 'yes'
OR `married` = 'no'
OR `married` IS NULL
)
AND age BETWEEN 18
AND 60
答案 1 :(得分:1)
查询中的条件需要在支持中弹出,您需要在搜索中应用一些以上的基本逻辑:
SELECT
*
FROM
contact
where
isdeleted = 0
AND contactgroup in ('Contactgroup1', '')
and media = 'sms'
AND
(
`gender` = 'female'
OR `gender` = 'male'
OR `gender` = 'null'
)
and age BETWEEN 18 AND 60
任何引入OR
语句的where子句基本上都会导致数据库忽略任何其他AND语句并返回任何匹配的数据。
在您的查询中,您有
OR `gender` = 'male'
OR `gender` = 'null'
这基本上意味着带回与此数据匹配的任何行。查询中的更改现在使得必须满足所有其他AND
语句 - 只要在括号内满足OR
个语句中的至少一个。
答案 2 :(得分:0)
在OR
周围使用括号 - 这样的条件:
SELECT
*
FROM
contact
WHERE isdeleted = 0
AND contactgroup in ('Contactgroup1', '')
AND media = 'sms'
AND (gender = 'female' OR gender = 'male' OR gender = 'null')
AND age BETWEEN 18 AND 60
这称为 Operator Precedence - AND
比OR
更重要,所以如果你不使用括号,就像你这样做:
SELECT
*
FROM
contact
WHERE (isdeleted = 0 AND contactgroup in ('Contactgroup1', '') and media = 'sms' AND gender = 'female')
OR (gender = 'male')
OR (gender = 'null' AND age BETWEEN 18 AND 60)