【问题标题】:Efficient way to insert values in an Oracle SQL table在 Oracle SQL 表中插入值的有效方法
【发布时间】:2019-02-27 19:17:53
【问题描述】:

我有两张类似的桌子

 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

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

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

【问题讨论】:

    标签: sql oracle sql-insert


    【解决方案1】:

    改用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 列上创建了索引?

    【讨论】:

    • 运行速度至少快 500 倍。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2021-10-13
    • 2012-05-12
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    • 2016-12-29
    • 2015-10-15
    • 2013-08-07
    相关资源
    最近更新 更多