作者:iamlaosong
我们经常需要查询新增的数据记录,比如新开发的客户,这就需要判断这些客户原来是否存在,用的比较多的是用not exists来区分新增客户。当数据库表记录很多时,查询速递需要很长时间,长得难以忍受。
例如,我们查询新增客户量收,语句如下:
select b.city,b.ssxs,a.clct_bureau_org_code,b.zj_mc,a.sender_cust_code,a.sender_dept_name, min(a.clct_date),max(a.clct_date),count(*) yjzl,sum(a.actual_total_fee) yjsr from tb_evt_mail_clct a, (select * from sncn_zd_jg where jgfl = 'sd') b where a.clct_bureau_org_code = b.zj_code and a.clct_date between to_date('2013-11-1', 'yyyy-mm-dd') and to_date('2013-11-10', 'yyyy-mm-dd') and length(a.sender_cust_code) = 14 and not exists (select 1 from tb_evt_mail_clct t where t.clct_date between to_date('2013-1-1', 'yyyy-mm-dd') and to_date('2013-10-31', 'yyyy-mm-dd') and t.sender_cust_code = a.sender_cust_code) group by b.city,b.ssxs,a.clct_bureau_org_code,b.zj_mc,a.sender_cust_code,a.sender_dept_name order by b.city,b.ssxs,a.clct_bureau_org_code,b.zj_mc,a.sender_cust_code,a.sender_dept_name
这个查询需要几个小时才能出来,如果换一种方法,采用下面的语句,只要几十秒就可以了。
select b.city,b.ssxs,a.clct_bureau_org_code,b.zj_mc,a.sender_cust_code,a.sender_dept_name, min(a.clct_date),max(a.clct_date),count(*) yjzl,sum(a.actual_total_fee) yjsr from tb_evt_mail_clct a, (select * from sncn_zd_jg where jgfl = 'sd') b, (select distinct t.sender_cust_code from tb_evt_mail_clct t where t.clct_date between to_date('2013-1-1', 'yyyy-mm-dd') and to_date('2013-10-31', 'yyyy-mm-dd')) c where a.clct_bureau_org_code = b.zj_code and a.clct_date between to_date('2013-11-1', 'yyyy-mm-dd') and to_date('2013-11-10', 'yyyy-mm-dd') and length(a.sender_cust_code) = 14 and a.sender_cust_code=c.sender_cust_code(+) and c.sender_cust_code is null group by b.city,b.ssxs,a.clct_bureau_org_code,b.zj_mc,a.sender_cust_code,a.sender_dept_name order by b.city,b.ssxs,a.clct_bureau_org_code,b.zj_mc,a.sender_cust_code,a.sender_dept_name