多个字段用and和or时要注意用括号。

多个字段用and和or时要注意用括号。

新技能get!

create table wly_test
(name1 varchar2(10),
number1 number(6),
score1 number(6),
score2 number(6),
score3 number(6));

插入数据:

NAME1 NUMBER1 SCORE1 SCORE2 SCORE3
1 wang 12345 54 31 111
2 zhao 21 12 34 231
3 qian 11 54 665 231
4 sun 222 21 342 12
5 li 1231 231 12 3123

--想要找出来 孙和李

1、错误的写法

select * from wly_test t
where t.score1 = 12
or t.score2 = 12
or t.score3 = 12
and t.number1 >100;

NAME1 NUMBER1 SCORE1 SCORE2 SCORE3
1 zhao 21 12 34 231
2 sun 222 21 342 12
3 li 1231 231 12 3123

2、正确的写法

select * from wly_test t
where t.number1 >100
and (t.score1 = 12
or t.score2 = 12
or t.score3 = 12);

NAME1 NUMBER1 SCORE1 SCORE2 SCORE3
1 sun 222 21 342 12
2 li 1231 231 12 3123

--------------------------------------------------4.27新增

如果不使用括号,查询时 or和and是有优先级的:先and后or。类似于计算中先计算乘法后计算加法。

例如:数据库中有1、2、3、4级的装卸和分拣共8条记录,最终会查出5条记录

select *
from test t
where t.acti_reso_name like '%装卸%'
or t.acti_reso_name like '%分拣%'
and t.field_level = '4';

会把4级的分拣和1、2、3、4级的装卸结果查出来~

原文地址:https://www.cnblogs.com/wly2009113/p/5362415.html