一个sql查询超过2和3或条件(mysql)

时间:2014-06-03 11:13:09

标签: php mysql sql

我想用以下条件查询mysql表

         where 
   1.      (type = 'Single Family') 
   2.   and (transaction = 'For sale'  )
   3.  and (price BETWEEN '0' and   '7500') 
   4.   and (beds >= '0' and baths >= '0')
   5.  and (city LIKE 'British columbia%' or neigh LIKE 'British columbia%' or province LIKE 'British columbia%');

结果应满足1& 2& 3& 4& 5个条件。

简而言之:

属于单身家庭的财产,它的出售和价格在0到7500之间,它的城市或邻近或省,如英国哥伦比亚。

为此我写了如下的查询

select *  
from   tablename  
where type = 'Single Family' 
    and transaction = 'For sale'  
    and price BETWEEN '0' 
    and   '7500' 
    and beds >= '0' 
    and baths >= '0'
    and city LIKE 'British columbia%' 
    or neigh LIKE 'British columbia%' 
    or province LIKE 'British columbia%';

它给出的结果不仅仅是' Single Family'但也像“菲尔兹'商业' ...

一样

然后我再次编写了仅返回type =' Single Family'但它在其他条件下失败了

select *  
from   tablename  
where transaction = 'For sale'  
    and price BETWEEN '0' 
    and   '7500' 
    and beds >= '0' 
    and baths >= '0'
    and city LIKE 'British columbia%' 
    or neigh LIKE 'British columbia%' 
    or province LIKE 'British columbia%' 
    and type = 'Single Family';

如何为我指定的条件编写正确的sql查询。

3 个答案:

答案 0 :(得分:4)

select *  
from   tablename  
where transaction = 'For sale'  
    and price BETWEEN '0' 
    and   '7500' 
    and beds >= '0' 
    and baths >= '0'
    and (city LIKE 'British columbia%' 
             or neigh LIKE 'British columbia%' 
             or province LIKE 'British columbia%' 
        )
    and type = 'Single Family';

这会将或条件视为1条款。

答案 1 :(得分:3)

select *
from   tablename 
where
     transaction = 'For sale'
     and price BETWEEN '0' and '7500'
     and beds >= '0' and baths >= '0'
     and city LIKE 'British columbia%'
     or neigh LIKE 'British columbia%'
     or province LIKE 'British columbia%'
     and type = 'Single Family'

与:

相同
select *
from   tablename 
where
     (
       transaction = 'For sale'
       and price BETWEEN '0' and '7500'
       and beds >= '0' and baths >= '0'
       and city LIKE 'British columbia%'
     )
     or neigh LIKE 'British columbia%'
     or (
       province LIKE 'British columbia%'
       and type = 'Single Family'
     )

使用括号隔离或。

select *
from   tablename 
where
     transaction = 'For sale'
     and price BETWEEN '0' and '7500'
     and beds >= '0' and baths >= '0'
     and (
       city LIKE 'British columbia%'
       or neigh LIKE 'British columbia%'
       or province LIKE 'British columbia%'
     )
     and type = 'Single Family'

答案 2 :(得分:2)

由于and的优先级高于or,因此您应该用括号括起or条件:

SELECT * 
FROM   tablename  
WHERE  type = 'Single Family' AND 
       transaction = 'For sale'  AND
       price BETWEEN '0' and '7500' AND
       beds >= '0' AND
       baths >= '0' AND 
       (city LIKE 'British columbia%' OR 
        neigh LIKE 'British columbia%' OR 
        province LIKE 'British columbia%') AND
       type = 'Single Family';