首页 > 解决方案 > 在 Oracle SQL 表中插入值的有效方法

问题描述

我有两张桌子

 create table nodes_tbl as (
 select 'a' as nodeid, 'some string' as dummy_string, 0 as subnetid from dual union all
 select 'b', 'qwe', 0 from dual  union all
 select 'c', 'asd', 0  from dual union all
 select 'd', 'zxc', 0 from dual union all
 select 'e', 'rty', 0 from dual);

 create table subnets as (
 select 'a' as nodeid, 1 as subnetid from dual union all
 select 'b', 2 from dual  union all
 select 'c', 2 from dual union all
 select 'd', 3 from dual union all
 select 'e', 4 as nodeid from dual);

拥有数百万条记录的连接可以快速运行。

select  n.NODEID, n.DUMMY_STRING, s.subnetid
   from nodes_tbl n, subnets s where s.nodeid=n.nodeid 

写入速度也很快

create table test_tbl as  n.NODEID, s.subnetid 
 from nodes_tbl n, subnets s where s.nodeid=n.nodeid  --10M records in 2s.

但是,当我尝试更新表并向列添加值时,查询非常慢

      UPDATE nodes_tbl n
       SET subnetid = (SELECT subnetid
                             FROM subnets s
                            WHERE s.nodeid = n.nodeid)
    WHERE EXISTS (
    SELECT subnetid  FROM subnets s
                            WHERE s.nodeid = n.nodeid)  --8 minutes for 100K records

为什么 insert 比create tablefromselect语句慢得多?执行此插入的最有效方法是什么?

我知道创建视图选项,但想避免它。

标签: sqloraclesql-insert

解决方案


请尝试MERGE

merge into nodes_tbl n
  using (select s.subnetid, s.nodeid 
         from subnets s
        ) x
  on (x.nodeid = n.nodeid)
when matched then update set
  n.subnetid = x.subnetid;

有什么改善吗?

顺便说一句,您是否NODEID在两个表中的列上都创建了索引?


推荐阅读