Oracle

Oracle 更新左連接

  • August 9, 2021

我有這個 MYSQL 程式碼,但我不確定如何將它轉換為 oracle 數據庫。任何幫助將不勝感激!

UPDATE product p
LEFT JOIN (
SELECT product_name, COUNT(*) AS quantity
FROM order_detail
GROUP BY product_name
) AS d ON d.product_name = p.product_name
SET p.order_quantity = IFNULL(d.quantity, 0);

您可以使用可更新視圖在 Oracle 中實現類似的語法。這是您將查詢編寫為選擇語句並更新的地方。但是,這需要保證連接不能是一對多的(此要求在最新版本中有所放寬,但我不希望這與此處相關)。

相反,您可以在正常update語句中使用標量子查詢。

UPDATE product p
SET    p.order_quantity = 
(
SELECT COUNT(*) AS quantity
FROM   order_detail d
WHERE  d.product_name = p.product_name
) 

您可以為此使用視圖

查看有關該問題的更多資訊

CREATE TABLE product (c1 NUMBER GENERATED ALWAYS as IDENTITY(START with 1 INCREMENT by 1), order_quantity int ,product_name varchar(110))
INSERT INTO product (order_quantity,product_name) VALUES (10,'A');
INSERT INTO product (order_quantity,product_name)  VALUES (11,'B');
CREATE TABLE order_detail (c1 NUMBER GENERATED ALWAYS as IDENTITY(START with 1 INCREMENT by 1),quantity int ,product_name varchar(110))
INSERT INTO order_detail (quantity,product_name) VALUES (5,'A')
INSERT INTO order_detail (quantity,product_name) VALUES (5,'A');
UPDATE (SELECT p.order_quantity,
                COALESCE(d.quantity,0) quantity
        FROM   product p LEFT JOIN (
SELECT product_name, COUNT(*) AS quantity
FROM order_detail GROUP BY product_name) d ON d.product_name = p.product_name

        ) ilv
SET ilv.order_quantity = ilv.quantity;

2 行受影響

SELECT * FROM product
C1 | 訂單數量 | 產品名稱
-: | -------------: | :-----------
 1 | 2 | 一種 
 2 | 0 | 乙 

db<>在這裡擺弄

引用自:https://dba.stackexchange.com/questions/297702