Home  >  Article  >  Database  >  10分钟小幅优化亿级数据查询

10分钟小幅优化亿级数据查询

WBOY
WBOYOriginal
2016-06-07 16:06:321052browse

前几天,一个用户研发QQ找我,如下: 自由的海豚。 16:12:01 岛主,我的一条SQL查不出来结果,能帮我看看不? 兰花岛主 16:12:10 多久不出结果? 自由的海豚 16:12:17 多久都没出结果,一直没看到结果过。 兰花岛主 16:12:26 呵呵,好。 兰花岛主 16:12:39

前几天,一个用户研发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的优化结束,其实,这个语句应该还有优化的空间,只是,用户说可以了那就可以了,因为优化是无止境的,而且,更进一步优化也许会需要更进一步的信息,且有时会需要更大的改动,鉴于各方面因素,文中对语句和计划进行了处理,记录于此,共勉!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:分区表Next article:数据库连接操作(一)