哆啦的時(shí)光機(jī)
2018-12-06 12:08:04
表TB中,在gid為1和2中,要把souceid和type同時(shí)相同的找出來,只取一條
id souceid type gid
1?? s1 ????? t1?????? 1
2?? s1 ????? t1?????? 2
3?? s2 ????? t2?????? 1
4?? s2 ????? t2?????? 2
5?? s3?????? t3?????? 1
我了解的三種方法分別利用in、join、row_number
1.select * from TB where id in (select Max(id) from TB where gid in(1,2) group by souceid,type)
2.select * from TB A join (select Max(id) id from TB where gid in(1,2) group by souceid,type) B on A.id=B.id
3.select * from (select id,souceid,type,gid,row_number() over (partition by souceid,type order by id) as rn) A where A.rn=1
請(qǐng)高手指正,哪種方法最高效亦或是有更好的改進(jìn)方法
4 回答

眼眸繁星
TA貢獻(xiàn)1873條經(jīng)驗(yàn) 獲得超9個(gè)贊
3效率最高.似乎應(yīng)該這樣寫.select * from (select id,souceid,type,gid,row_number() over (partition by souceid,type order by id) as rn from TB) A where A.rn=1
直接得出結(jié)果.
?
1,2 都分兩步進(jìn)行,最后都涉及到聚合運(yùn)算.
?
我的理解, 有不對(duì)的地方,歡迎指出.謝謝!

撒科打諢
TA貢獻(xiàn)1934條經(jīng)驗(yàn) 獲得超2個(gè)贊
不一定,話說分析函數(shù)挺費(fèi)效率的.....在大數(shù)據(jù)量的時(shí)候
整體來看,效率最高的是2或3,數(shù)據(jù)量大的話應(yīng)該是2;
gid in(1,2) ,改成 gid = 1 or gid = 2;
效率能高一點(diǎn);
如果想效率最高的話,應(yīng)該將其合并至一句:
很簡單, GID最好加上索引;如果數(shù)據(jù)一直是1,2+位圖索引;
- 4 回答
- 0 關(guān)注
- 508 瀏覽
添加回答
舉報(bào)
0/150
提交
取消