0

好的,所以我用我的 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

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

这看起来正确吗?还是可以建造得更好?

4

3 回答 3

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
)
于 2013-04-10T10:51:18.083 回答
1

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

于 2013-04-10T10:50:50.453 回答
1

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

根据经验,最好不要在同一级别的表达式上混合ands 和s。or

您应该将查询重写为:

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两个表达式之间的一个。第一个表达式(带有likes 的部分)只有当它的任何部分都为真时才为真,而第二部分(numeric_price 检查)只有当它的两个部分都为真时才为真。只有当两个子表达式都为真时,整个事情才为真。

于 2013-04-10T10:55:44.597 回答