select id,name,addtime from news 我要取出ID不重复的数据,难道非得这样:select distinct id,
(select top 1 name from news where news .id=id) name,
(select top 1 addtime from news where news .id=id) addtime from news 有没有简单点的SQL??
(select top 1 name from news where news .id=id) name,
(select top 1 addtime from news where news .id=id) addtime from news 有没有简单点的SQL??
inner join
(select max(addtime) mxt,cid from news group by id) b
on cid=id and mxt=addtime
或者用 not exists
或者用 1>count法
基本都是一样的
GROUP BY ID
inner join最稳定. 先分组聚合,再连接.
not exists的速度比较多变,依具匹配度. 每查一条记录都要查同id的记录中是否有addtime比当前记录大的,一直要找完所有同id的记录才能排除当前记录,进入下一条记录再重复上述操作,匹配度越高越快. 这个是从同id相同的记录中找一条最大的,所以匹配度是1/n.
count法,算法比较同 not exists法. 有点不同的是,他对同id的记录count聚合,并不在满足某条件时退出聚合. 速度一般稍慢于 not exists.
还有就是in的写法. 也快不了哪去. 推荐用 inner join.
如果是用 exists的法,一有匹配记录即退出当前查找,匹配度越高效率越好.
大多数情况下,能用 exists的我就尽量用.能不用 not exists的就尽量不用,而改用join
select DISTINCT id,MAX(name),MAX(addtime) from news
GROUP BY ID
这种写法写出来的是聚合结果,不是某一条记录. 二者是有区别的.当然,用哪种要看楼主要求了.
GROUP BY ID
这个好象速度快点 用这个 结贴 谢谢大家