如何遍历记录然后搜索另一个 table 如果没有找到然后在从另一个 table 在 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 个 table
我需要从 table1 中获取每个 id,如果它存在,则需要查看 table2 然后不做任何其他明智的事情我需要查看 table3 如果我是能够找到它,然后获取 phone 编号以及 table 中的详细信息 1 将其插入 table2。如何在 oracle 中执行此操作?
你可以试试这个:
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<>fiddle here
我的数据库中有 3 个 table
我需要从 table1 中获取每个 id,如果它存在,则需要查看 table2 然后不做任何其他明智的事情我需要查看 table3 如果我是能够找到它,然后获取 phone 编号以及 table 中的详细信息 1 将其插入 table2。如何在 oracle 中执行此操作?
你可以试试这个:
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<>fiddle here