在Oracle SQL表中插入值的有效方法

时间:2019-02-27 19:17:53

标签: sql oracle sql-insert

我有两个表,

 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

为什么从create table语句插入比select慢得多? 进行插入的最有效方法是什么?

我了解创建视图选项,但想避免使用它。

1 个答案:

答案 0 :(得分:3)

改为尝试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列上都创建了索引?