替代 Where Exist 子句 MySQL

问题描述

我有这个 select 语句,它需要很长时间才能在更大的数据集上运行

select lookup_svcscat_svcscatnew.SVCSCAT_NEW_DESC as svc_type,enrolid,msclmid,dx1,dx2,dx3,proc1,msk_cpt_mapping.surg_length_cd as SL_CD,msk_cpt_mapping.days as day_window,o.svcdate_form,pay,table_label
from ccaeo190_ky o
    left join lookup_svcscat_svcscatnew on o.svcscat = lookup_svcscat_svcscatnew.svcscat
    left join msk_cpt_mapping on o.proc1 = msk_cpt_mapping.cpt_code
where EXISTS 
        (
        select 1 
        from eoc_op_mapping e
        where e.msclmid = o.msclmid
            and e.enrolid = o.enrolid
            and proc1 =27447
        )
ORDER BY svcdate_form,msclmid;

我想返回我的 ccaeo190_ky 表中满足表 eoc_op_mapping 上的 where EXISTS 子句要求的任何行。有没有办法使用连接或选择语句来实现这些结果?

我在想:

select lookup_svcscat_svcscatnew.SVCSCAT_NEW_DESC as svc_type,o.enrolid,o.msclmid,table_label
from ccaeo190_ky o
    left join lookup_svcscat_svcscatnew on o.svcscat = lookup_svcscat_svcscatnew.svcscat
    left join msk_cpt_mapping on o.proc1 = msk_cpt_mapping.cpt_code
    inner join
        (select msclmid,SUM(IF(proc1 = 27447,1,0)) AS cpt 
        from eoc_op_mapping 
        group by enrolid
        HAVING cpt > 0) e 
on e.enrolid = o.enrolid
group by o.enrolid;

但我不知道这是否朝着正确的方向

解决方法

通常 EXISTS 的性能比连接更好。

如果您想尝试加入,这相当于您的 WHERE EXISTS

.......................................................
inner join (
  select distinct msclmid,enrolid
  from eoc_op_mapping
  where proc1 = 27447
) e on e.msclmid = o.msclmid and e.enrolid = o.enrolid
.......................................................

如果 distinct 中没有重复的 msclmid,enrolid 组合,您可以删除 eoc_op_mapping