以下查询
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效果很好,但第三个没有。
答案 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