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

不产生任何错误,并且实际工作,但有一个小问题:这部分

AND workshop_date >= NOW()

不过滤任何东西,尝试用等号替换比较符号,并检索相同的列表。

前两个 AND 效果很好,但第三个不行。

4

3 回答 3

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

于 2012-09-05T17:31:58.100 回答
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

这将检查车间邮政编码,然后检查您的其他标准。

于 2012-09-05T17:32:14.317 回答
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
于 2012-09-05T17:31:44.080 回答