sql语句exists,复杂语句总结

1、select a.* from tb a where val = (select max(val) from tb where name = a.name) order by a.name
分组查询各组最大值;
牛逼之处在于where name = a.name,用这句进行分组,然后组内找出最大值。


2、select a.* from tb a where not exists(select 1 from tb where name = a.name and val > a.val)
分组查询各组最大值;
牛逼之处在于两组进行两两比较,找出符合条件的a值,然后在外面的查询中找到a对应数据。


3、select a.* from student a where exists (select count(*) from student where class = a.class and score > a.score having count(*) < 3) order by a.class, a.score desc
分组排序并找出最大的3个值;
牛逼之处在于两组中的每个元素进行两两对比,然后找出满足条件的a值,然后再外面的查询中找出a对应的数据。

 

原文地址:https://www.cnblogs.com/qiaoer1993/p/12158496.html