MYSQL多个OR和AND

时间:2013-04-10 10:49:04

标签: mysql sql

好的,所以我用我的PHP脚本构建了这个查询:

SELECT * 
FROM sale_properties 
WHERE advert_heading LIKE '%harnham%' 
   OR main_advert LIKE '%harnham%' 
   OR advert2 LIKE '%harnham%' 
   OR advert3 LIKE '%harnham%' 
   OR street LIKE '%harnham%' 
   OR district LIKE '%harnham%' 
   OR town LIKE '%harnham%' 
   OR county LIKE '%harnham%' 
   OR area LIKE '%harnham%' 
   OR postcode LIKE '%harnham%' 
   AND numeric_price >= 150000.00 
   AND numeric_price <= 152000.00

现在,这确实给了我一些结果,但是,我想基本上在数据库中搜索关键字并在价格范围内。上面的查询确实给了我关键字,但似乎忽略了大部分价格范围。

这看起来是否正确?或者它可以更好地建造?

3 个答案:

答案 0 :(得分:5)

尝试使用括号......

SELECT * FROM sale_properties WHERE
 (
    advert_heading LIKE '%harnham%' OR
    main_advert LIKE '%harnham%' OR
    advert2 LIKE '%harnham%' OR
    advert3 LIKE '%harnham%' OR
    street LIKE '%harnham%' OR
    district LIKE '%harnham%' OR
    town LIKE '%harnham%' OR
    county LIKE '%harnham%' OR
    area LIKE '%harnham%' OR
    postcode LIKE '%harnham%'
) AND (
    numeric_price >= 150000.00 AND
    numeric_price <= 152000.00
)

答案 1 :(得分:1)

这就像数学运算一样,你必须使用括号。

答案 2 :(得分:1)

虽然有一些规则如何评估or-和表达式(运算符优先级表和类似的东西),但这些很难正确,并且很难调试。

最好是,作为一条经验法则,您尝试永远不要将andor混合在表达式的同一级别上。

您应该将查询重写为:

SELECT * 
FROM sale_properties 
WHERE 
     (advert_heading LIKE '%harnham%' 
      OR main_advert LIKE '%harnham%' 
      OR advert2 LIKE '%harnham%' 
      OR advert3 LIKE '%harnham%' 
      OR street LIKE '%harnham%' 
      OR district LIKE '%harnham%' 
      OR town LIKE '%harnham%' 
      OR county LIKE '%harnham%' 
      OR area LIKE '%harnham%' 
     OR postcode LIKE '%harnham%')
   AND 
     (numeric_price >= 150000.00 
      AND numeric_price <= 152000.00)

因此它基本上成为两个表达式之间的单个and。第一个表达式(具有like s的部分)仅在其任何部分为真时才为真,而第二个部分(numeric_price检查)仅在其两个部分均为真时才为真。只有当两个子表达式都为真时,整个事情才会成立。