根据 select 查询更新记录

Update records based on select query

我有一张桌子1:

u_a_id  d_c_s   c_nm    c_seq   r_c_p
1       908     Test1   1       20
10      908     Test1   1       21
11      908     Test1   1       12
12759   908     Test1   1       31
12759   908     Test1   1       32
12861   878     Test2   1       43
12861   878     Test2   1       44

我还有一张桌子2:

d_c_s   c_nm    c_seq   n_min_d_c_s     n_min_c_nm
908     Test1   1       12001           Test1, First
878     Test2   1       12002           Test2, First

我需要更新 table1 ==>

更新条件为:

输出如下:

u_a_id  d_c_s   c_nm            c_seq   r_c_p
1       908     Test1           1       20
10      908     Test1           1       21
11      908     Test1           1       12
12759   12001   Test1, First    1       31
12759   908     Test1           1       32
12861   12002   Test2, First    1       43
12861   878     Test2           1       44

创建 UPDATE/MERGE 查询以实现此目的的最佳方法是什么?

DBFIDDLE 演示 - Link

您可以使用 MERGE 语句,如下所示:

MERGE INTO TABLE1 T1 
USING (
       SELECT
           MIN(TI1.R_C_P) AS R_C_P,
           TI1.U_A_ID,
           TI1.D_C_S,
           TI1.C_NM,
           TI1.C_SEQ,
           TI2.N_MIN_C_NM,
           TI2.N_MIN_D_C_S
       FROM
           TABLE1 TI1
           JOIN TABLE2 TI2 
           ON ( TI1.D_C_S = TI2.D_C_S
                AND TI1.C_NM = TI2.C_NM
                AND TI1.C_SEQ = TI2.C_SEQ
                AND TI1.C_NM NOT IN (
               'VOID',
               'WRONG'
           ) )
       GROUP BY
           TI1.U_A_ID,
           TI1.D_C_S,
           TI1.C_NM,
           TI1.C_SEQ,
           TI2.N_MIN_C_NM,
           TI2.N_MIN_D_C_S
       HAVING
           COUNT(1) > 1
   )
T2 ON ( T1.C_SEQ = T2.C_SEQ
        AND T1.R_C_P = T2.R_C_P )
WHEN MATCHED THEN 
UPDATE 
SET T1.C_NM = T2.N_MIN_C_NM,
T1.D_C_S = T2.N_MIN_D_C_S
WHERE
    T1.D_C_S = T2.D_C_S
    AND T1.C_NM = T2.C_NM 
    AND T1.U_A_ID = T2.U_A_ID -- ADDED THIS CONDITION
-- WHERE CONDITION IS USED AS IT CAN NOT BE USED INSIDE ON CLAUSE
-- TO AVOID ERROR : ORA-38104: Columns referenced in the ON Clause cannot be updated

Demo DB Fiddler

干杯!!