1. select * from student s where s.id in (20,30);

查询id是20或者是30,等同于select * from student s where s.id = 20 or s.id = 30;

2.select * from student s where s.id in (select age from student);

查询id是age数组里面的,单个字段只能in查询结果是单行的。

很明显后面括号的 select age from student 查出来只有age这一列,假如括号的查询查出来的age是下面图列

那么此时查询就等价于select * from student s where s.id in (64,57,32,24,35,55);

3.select * from student s where (s.class , s.score) in (select class , max(score) from student group by class)

既然能单个字段in单行结果,那么多个字段就能in多行结果了

这个sql表示:查询每个班级中分数最高的学生的所有数据

注意,此时的name和class是不会错位的,你本来就是按着匹配的class和score去in匹配class、score的结果集,所以数据不会出错的。

如果你写成这样:

select * from student s where s.class in (select class from student group by class ) and s.score in (select max(score) from student group by class);

就把class和score的关系分开了,分开后就可能出现结果列错位的情况,可能名字和他的分数对不上。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐