关于Mysql的Group By

来源:百度知道 编辑:UC知道 时间:2024/09/20 02:47:30
exampletable
id type name important
1 a b 2
2 a c 1
3 b g 4
4 b h 3
如何写一个sql 选出 type为a或者b 并且按照important 倒排的各第一条记录
也就是选出
1 a b 2
3 b g 4
TO一楼 谢谢
如果type还有其他很多种类(就是选择的时候不知道type有多少种值) 怎么写sql呢
TO二楼/三楼
用子查询是可以的
不知道有没有不用子查询的 呵呵

Select * From (Select * From exampletable Order By important Desc) As tmp Group By type

括号里的子查询是让结果按important倒序排列。
外边的查询是值选出每个type的一条记录。

select id,type,name,important
from exampletable
where type = 'a'
order by important desc limit 1
union all
select id,type,name,important
from exampletable
where type = 'b'
order by important desc limit 1

select * from (select * from exampletable order by important desc) group by type order by important desc;

试一下子查询,可以的话告诉我

select top 1 *
from exampletable
where type='a'
order by important desc
union
select top 1 *
from exampletable
where type='b'
order by important desc