如何在Oracle中将外部联接选择查询转换为MERGE

时间:2018-11-18 23:36:08

标签: sql oracle merge sql-update oracle12c

如何将这种简单的外部联接转换为MERGE,以将FT.SS更新为选定行的特定值:

SELECT FT.SS FROM FT_T FT LEFT OUTER JOIN DC_T DC
    ON FT.ID = DC.ID AND FT.CN = DC.CN
WHERE FT.GID = 'AB' AND SS = 'C' AND FT.DEL = 'N' AND PR_S IS NULL AND EN_S IS NULL
AND (DC.ID IS NULL OR DC.SIGNED IS NULL); 

使用UPDATE相对容易:

UPDATE FT_T FTX
SET FTX.SS = 'X'
WHERE FT.GID = 'AB' AND SS = 'C' AND FT.DEL = 'N' 
    AND PR_S IS NULL AND EN_S IS NULL 
    AND (FTX.ID, FTX.CN) = (
       SELECT FT.ID, FT.CN FROM FT_T FT LEFT OUTER JOIN DC_T DC
           ON FT.ID = DC.ID AND FT.CN = DC.CN
       WHERE FT.GID = 'AB' AND SS = 'C' AND FT.DEL = 'N' AND PR_S IS NULL AND EN_S IS NULL 
         AND (DC.ID IS NULL OR DC.SIGNED IS NULL)
)

但是可以用MERGE吗?

1 个答案:

答案 0 :(得分:1)

您的合并语句如下:

MERGE INTO ft_t tgt
USING (SELECT ft.id,
              ft.cn
       FROM   ft_t ft
              LEFT OUTER JOIN dc_t dc ON ft.id = dc.id AND ft.cn = dc.cn
       WHERE  ft.gid = 'AB'
       AND    ft.ss = 'C'
       AND    ft.del = 'N'
       AND    ft.pr_s IS NULL
       AND    ft.en_s IS NULL
       AND    (dc.id IS NULL OR dc.signed IS NULL)) src
 ON (tgt.id = src.id AND tgt.cn = src.cn) -- assuming these two columns are the primary key for the ft_t table
WHEN MATCHED THEN
  UPDATE SET tgt.ss = 'X';