我有一张桌子:
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
==>
table1.c_nm
= table2.n_min_c_nm
table1.d_c_s
= table2.n_min_d_c_s
要更新的条件是:
select u_a_id, d_c_s, c_nm, c_seq, count(*) cnt from table1 where c_nm not in ('VOID', 'WRONG') group by u_a_id, d_c_s, c_nm, c_seq having count(*) > 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 12001 Test1, First 1 31
12759 908 Test1 1 32
12861 12002 Test2, First 1 43
12861 878 Test2 1 44
创建UPDATE / MERGE查询以实现此目标的最佳方法是什么?
DBFIDDLE DEMO-Link
答案 0 :(得分:1)
您可以使用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
干杯!
答案 1 :(得分:0)
UPDATE table1 t1
SET t1.d_c_s =
(select
t2.n_min_d_c_s
from
table2 t2
WHERE t1.d_c_s=t2.d_c_s
AND t1.c_nm=t2.c_nm
AND t1.c_seq=t2.c_seq),
t1.c_nm =
(select
t2.n_min_c_nm
from
table2 t2
WHERE t1.d_c_s=t2.d_c_s
AND t1.c_nm=t2.c_nm
AND t1.c_seq=t2.c_seq)
WHERE t1.r_c_p in (
SELECT min(r_c_p) min_r_c_p
from table1
where c_nm not in ('VOID', 'WRONG')
group by u_a_id, d_c_s, c_nm, c_seq
having count(*) > 1
);
https://dbfiddle.uk/?rdbms=oracle_18&fiddle=870bca3d3cfb72e4638f678b9bf05199