MYSQL中and和or一起作为where条件 查询结果错误问题
1、先创建表
create table user_info(
id int auto_increment primary key comment '主键id',
name varchar(20) comment '姓名',
sex tinyint comment '性别 1 男 2 女',
age int comment '性别',
id_card varchar(20) comment '身份证号',
create_time datetime comment '创建时间'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci ROW_FORMAT=DYNAMIC comment '用户信息表';
insert into user_info(name, sex, age, id_card, create_time) values ('小明',1,18,null,now()),
('小红',2,16,null,now()),
('小张',1,17,null,now()),
('小花',1,18,null,now()),
('小李',2,16,null,now()),
('小王',1,17,null,now()),
('小白',2,17,null,now()),
('笑笑',1,17,null,now());
2、假如想要查询 sex = 2 且年龄为17或18的人员信息
最初写到的sql为
select * from user_info where sex = 2 and age = 17 or age = 18;
查询结果为
很明显的查询结果是错误的,并不是我们想要的结果
再次修改sql
select * from user_info where age = 17 or age = 18 and sex = 2 ;
查询结果如下图
很明显查询结果也是不对的
查询一番之后,原来是mysql中and和or执行优先级的问题,
MySQL中,AND的执行优先级高于OR。也就是说,在没有小括号()的限制下,总是优先执行AND语句,再执行OR语句。
select * from table where 条件1 AND 条件2 OR 条件3
等价于
select * from table where ( 条件1 AND 条件2 ) OR 条件3
select * from table where 条件1 AND 条件2 OR 条件3 AND 条件4
等价于
select * from table where ( 条件1 AND 条件2 ) OR ( 条件3 AND 条件4 )
3、上面的查询再次修改之后:
select * from user_info where sex = 2 and (age = 17 or age = 18);
查询结果:
查询结果正确,完成,在下次使用and和or的时候一定需要注意其优先级的问题。使用or时 可以使用小括号进行连接。