在项目中遇到这样一个问题,困扰了我几天 SQL语句如下:
select * from t_instance where instance_code like '%姓名%' or instance_name '%姓名%' and classfired='cloumn'
我想要的结果的条件是:1. instance_code like '%姓名%' or instance_name '%姓名%'
2. classfired='cloumn'
但是结果并非如此,出现了 classfired !='cloumn'的结果,但是却匹配了 instance_name '%姓名%' and classfired='cloumn'
为什么呢
原来这个SQL的执行是这样的:
select * from t_instance where instance_code like '%姓名%' or instance_name '%姓名%' and classfired='cloumn'
修改为:
select * from t_instance where classfired='cloumn' and instance_code like '%姓名%' or instance_name '%姓名%'
依然不正确
呵呵,发现问题了:
where 后面如果有and,or的条件,则or自动会把左右的查询条件分开,即先执行and,再执行or。原因就是:and的执行优先级最高!
关系型运算符优先级高到低为:not and or
问题的解决办法是:
通常使用‘()’可以改变运算符的优先级 来改变执行顺序!!!!
上面我所需要的SQL语句是这样的
select * from t_instance where classfired='cloumn' and (instance_code like '%姓名%' or instance_name '%姓名%' )