现在,我正在使用此查询选择数据(简称):
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)
问题是需要花费很多时间才能完成,执行计划如下:
最近需要处理大约2000万行(图片)才能获得2.5万行。
有没有更好的方法来加入具有条件的PTY表?
答案 0 :(得分:4)
IIF
条件中使用的 ON
函数会使查询无法进行查询
如果这些列person.FORGN_ISTC_IND
,person.FORGN_ISTC_IND
,partner.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
。