簡體   English   中英

如何遍歷記錄然后搜索到另一個表,如果沒有找到,然后在從 oracle 中的另一個表中獲取記錄后插入它?

[英]How to loop over records and then search into another table and if not found then insert it after fetching records from another table in oracle?

我的數據庫中有 3 個表
表格1 表 2 表3

我需要從 table1 中獲取每個 id,如果它存在則需要查看 table2,然后對該 ID 不采取任何其他措施,如果我能夠找到它,我需要查看 table3,然后獲取電話號碼以及來自的詳細信息表 1 將其插入到表 2 中。如何在 oracle 中執行此操作?

你可以試試這個:

db<>小提琴

INSERT INTO table_2
SELECT table_1.id, table_1.name, table_1.gender, table_1.age, table_3.phone_num
FROM table_1
INNER JOIN table_3 ON table_1.id = table_3.id
WHERE table_1.id NOT IN (SELECT id FROM table_2);

您可以使用MERGE語句來避免兩次訪問Table2

MERGE INTO table2 dst
USING (
  SELECT t1.*, t3.phone_num
  FROM   table1 t1
         LEFT OUTER JOIN table3 t3
         ON (t1.id = t3.id)
) src
ON (src.id = dst.id)
WHEN NOT MATCHED THEN
  INSERT (id, name, gender, age, phone_num)
  VALUES (src.id, src.name, src.gender, src.age, src.phone_num);

如果您還想更新現有行,則可以在同一語句中執行此操作:

MERGE INTO table2 dst
USING (
  SELECT t1.*, t3.phone_num
  FROM   table1 t1
         LEFT OUTER JOIN table3 t3
         ON (t1.id = t3.id)
) src
ON (src.id = dst.id)
WHEN MATCHED THEN
  UPDATE
  SET name      = src.name,
      gender    = src.gender,
      age       = src.age,
      phone_num = src.phone_num
WHEN NOT MATCHED THEN
  INSERT (id, name, gender, age, phone_num)
  VALUES (src.id, src.name, src.gender, src.age, src.phone_num);

db<> 在這里擺弄

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM