mysql AND在查询中使用两次不起作用

时间:2012-09-05 17:29:26

标签: mysql

以下查询

SELECT * FROM workshops 
WHERE workshop_zipcode LIKE '75___' 
  OR workshop_zipcode LIKE '77___' 
  AND workshop_category = 14 
  AND active = 1 
  AND workshop_date >= NOW() 
ORDER BY workshop_date ASC

不产生任何错误,实际上有效,但有一点问题:这部分

AND workshop_date >= NOW()

不要过滤任何内容,请用相等的符号替换比较符号,并检索相同的列表。

两个第一个AND效果很好,但第三个没有。

3 个答案:

答案 0 :(得分:5)

您需要为OR条件加上括号,如下所示:

SELECT * FROM workshops 
WHERE (workshop_zipcode LIKE '75___' 
OR workshop_zipcode LIKE '77___')
AND workshop_category = 14 
AND active = 1 
AND workshop_date >= NOW() 
ORDER BY workshop_date ASC

没有括号,你实质上就是这样称呼:

SELECT * FROM workshops 
WHERE workshop_zipcode LIKE '75___' 
OR (workshop_zipcode LIKE '77___'
AND workshop_category = 14 
AND active = 1 
AND workshop_date >= NOW())
ORDER BY workshop_date ASC

这是因为AND是在OR之前计算的。参见此参考资料

http://dev.mysql.com/doc/refman/5.0/en/operator-precedence.html

答案 1 :(得分:1)

这可能是运营商优先级的问题。

SQL将首先评估所有AND语句,然后评估OR语句;如果你在它们周围放置括号,你可能会得到你期望的结果:

SELECT * FROM workshops 
WHERE (workshop_zipcode LIKE '75___' 
OR workshop_zipcode LIKE '77___')
AND workshop_category = 14 
AND active = 1 
AND workshop_date >= NOW() 
ORDER BY workshop_date ASC

这将检查研讨会的zipcodes,然后检查其余的标准。

答案 2 :(得分:0)

试试这个:

SELECT * FROM workshops 
WHERE ( workshop_zipcode LIKE '75___' 
OR workshop_zipcode LIKE '77___' )
AND workshop_category = 14 
AND active = 1 
AND workshop_date >= NOW() 
ORDER BY workshop_date ASC