选择查询中条件连接的性能问题

时间:2018-01-10 16:25:07

标签: sql sql-server

现在,我正在使用此查询选择数据(简称):

SELECT person.*, pty.*
FROM PERSON person
     LEFT JOIN PARTNER partner 
     ON partner.FK_BPE_ISTC_ID = person.BSPE_ISTC_ID
     INNER JOIN PTY pty 
     ON pty.PTY_ISTC_ID = IIF(person.FORGN_ISTC_IND != 0, person.FORGN_ISTC_IND, partner.FRGN_ISTC_ID)

问题是需要花费很多时间才能完成,执行计划如下:

Execution plan

最近需要处理大约2000万行(图片)才能获得2.5万行。

有没有更好的方法来加入具有条件的PTY表?

2 个答案:

答案 0 :(得分:4)

IIF条件中使用的

ON函数会使查询无法进行查询

如果这些列person.FORGN_ISTC_INDperson.FORGN_ISTC_INDpartner.FRGN_ISTC_ID

中的任何列都有索引,则查询效果会更好
SELECT person.*,
       pty.*
FROM   PERSON person
       LEFT JOIN PARTNER partner
              ON partner.FK_BPE_ISTC_ID = person.BSPE_ISTC_ID
       INNER JOIN PTY pty
               ON ( person.FORGN_ISTC_IND != 0
                    AND pty.PTY_ISTC_ID = person.FORGN_ISTC_IND )
                   OR pty.PTY_ISTC_ID = partner.FRGN_ISTC_ID

答案 1 :(得分:3)

多个左连接:

SELECT person.*, 
       COALESCE(ptyp.col1, ptypa.col1) as col1,
       . . .
FROM PERSON p LEFT JOIN PARTNER
     partner pa
     ON pa.FK_BPE_ISTC_ID = p.BSPE_ISTC_ID LEFT JOIN
     pty ptyp
     ON p.FORGN_ISTC_IND <> 0 AND ptyp.PTY_ISTC_ID = p.FORGN_ISTC_IND LEFT JOIN
     pty ptypa
     ON pty.PTY_ISTC_ID = 0 AND ptypa.PTY_ISTC_ID = pa.FRGN_ISTC_ID;

SQL Server可以更好地优化简单的join条件。您需要在select

中选择适当的值