在实际环境中我们经常会用到Group By去去重。但是当去重还需要加上条件的时候Group By会有使用误区。
如有user表。
- user_id user_name age heigh class
- liming 李明 13 170 1
- zhangsan 张三 14 168 2
- wangwu 王五 12 171 1
- zhaoliu 赵六 13 168 2
查询要求:查出每个班级(class)中身高(height)最高的,若身高相同则按照年龄排序,步骤如下:
1.查询出每个班级最高的身高
select max(height) as height,class from user group by class;
2.根据1查询出来的数据,查询出每个班级身高最高的人。
select max(age) as age,u.height,u.class from user u,
(select max(height) as height,class from user group by class) t
where u.height=t.height an u.class=t.class group by u.height ;
3.根据2的查询结果,关联user表就可以查询出结果
select * from user u1,(select max(age) as age,u.height,u.class from user u,
(select max(height) as height,class from user group by class) t
where u.height=t.height an u.class=t.class group by u.height)t1
where u1.age=t1.age and u1.height=t1.height and u1.class= t1.class ;
结果可能会出现一个班级多个人,若需要一个班级只有一个人需要再加上一个Group By.
误区:很多人会使用如下的SQL进行查询。
select * from (select * from user order by height desc,age desc) t
group by t.class.
该SQL查询出来的结果是未知的,任何情况都有可能。