SQL優化(SQL TUNING)之10分鍾完成億級數據量性能優化(SQL調優)


前幾天,一個用戶研發QQ找我,如下:

 

自由的海豚。 16:12:01

島主,我的一條SQL查不出來結果,能幫我看看不?

蘭花島主 16:12:10

多久不出結果?

自由的海豚 16:12:17

多久都沒出結果,一直沒看到結果過。

蘭花島主 16:12:26

呵呵,好。

蘭花島主 16:12:39

發下sql和執行計划。

 

自由的海豚 16:12:55

select n.c1, n.c2,n.c3,n.c4,n.c5
  from (select  count(t.c1), t.c1, t.c2,t.c3,t.c4,t.c5
          from tab1 t
         where t.c2 not in ('val1','val2','val3','val4','val5')
         group by t.c1, t.c2,t.c3,t.c4,t.c5) n
 where not exists
 (select * from (
select  count(s.c2), s.c1, s.c2                     
  from (select m.c1, m.c2,m.c3,m.c4,m.c5
          from tab1 m
         where exists (select c1
                  from tab2 n
                 where c2 > sysdate - 14
                   and m.c1 = n.c1)
           and m.c1 is not null
           and m.c2 not in  ('val1','val2', 'val3', 'val4', 'val5')) s
 group by s.c1, s.c2) t1 where t1.c2 = n.c2)
   and n.c1 is not null;

蘭花島主 16:13:12

這兩張表大嗎?

自由的海豚 16:13:16

tab1小,tab2億級以上,兩周數據在幾千萬。

蘭化島主 16:13:22

OK。

蘭花島主 16:16:29

這么改下sql吧:

with t1 as(
select count(t.c1), t.c1,t.c2,t.c3,t.c4,t.c5
  from tab1 t
 where t.c2 not in ('val1','val2','val3','val4','val5')
   and c1 is not null
 group by t.c1, t.c2,t.c3,t.c4,t.c5) 
select t1.c1,t1.c2,t1.c3,t1.c4,t1.c5
  from t1 
where not exists(
select /*+ use_hash(m,n)*/ m.c1, m.c2,m.c3,m.c4,m.c5
   from t1 m,tab2 n
  where n.c2 > sysdate - 14
    and m.c1 = n.c1
    and t1.c2 = m.c2);

蘭花島主 16:16:43

取下執行計划。

自由的海豚 16:16:57

好的。

自由的海豚 16:17:25

蘭花島主 16:17:57

好的,試試吧。

自由的海豚 16:19:28

出結果了,37s

 

蘭花島主 17:20:21

 嗯,好。

蘭花島主 17:20:34

 這樣可以嗎?

自由的海豚 17:20:47

 可以了可以了

蘭花島主 17:21:11

 嗯,好,那就先這樣,不繼續調了。

自由的海豚 17:21:30

 恩 好的 謝謝島主 

蘭花島主 17:21:53

 不客氣,忙吧,有事兒聯系。

自由的海豚 17:22:18

 恩,您忙。。。

至此,對用戶這個sql的優化結束,其實,這個語句應該還有優化的空間,只是,用戶說可以了那就可以了,因為優化是無止境的,而且,更進一步優化也許會需要更進一步的信息,且有時會需要更大的改動,鑒於各方面因素,文中對語句和計划進行了處理,記錄於此,共勉!

 

 









免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM