我有這個 sql 查詢
(select x.a, x.b, x.c, x.d
from tableX x
where x.a IS NOT NULL
minus
select y.a, y.b, y.c, y.d
from tableY y);
上面的查詢回傳了所有 tableX 資料,這與 tableY 不同。回傳多個元組
證據:
當我運行上面的查詢時,我得到了這個結果:
| 一種 | 乙 | C |
|---|---|---|
| 1 | 43 | 65 |
| 2 | 66 | 333 |
當我從 tableY 中選擇資料時,我得到了這個:
| 一種 | 乙 | C |
|---|---|---|
| 1 | 54 | 65 |
| 2 | 88 | 567 |
tableY 資料是正確的資料,所以我想用 tableY 中的資料更新從第一個查詢(帶有 MINUS 子句的查詢)回傳的所有元組。
在更新子句之后,當我從 tableX 中選擇資料時的預期結果應該是:
| 一種 | 乙 | C |
|---|---|---|
| 1 | 54 | 65 |
| 2 | 88 | 567 |
執行此 UPDATE 子句的最有效方法是什么?
uj5u.com熱心網友回復:
在 oracle 上,我發現 MERGE 語法比 UPDATE 語法更有用...
MERGE INTO
tablex x
USING
tabley y
ON (y.a = x.a)
WHEN MATCHED THEN UPDATE
SET
x.b = y.b,
x.c = y.c
WHERE
LNNVL(x.b = y.b)
OR
LNNVL(x.c = y.c)
編輯:添加 where 子句以避免冗余更新,下面的評論。
uj5u.com熱心網友回復:
update tablex
set (b, c) = (select b, c from tabley where tabley.a = tablex.a)
where exists (select 1 from tabley where tabley.a = tablex.a);
為了減少交易規模,添加 xb <> yb 或 xc <> yc:
update tablex
set (b, c) = (select b, c from tabley where tabley.a = tablex.a)
where exists (select 1 from tabley
where tabley.a = tablex.a
and (LNNVL(tabley.b = tablex.b) or LNNVL(tabley.c = tablex.c)));
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/368564.html
