使用新的ID复制数据-Oracle SQL

时间:2019-06-04 13:10:24

标签: sql oracle

我有一张桌子:

u_a_id   c_id    c_val
1        100     abc
1        101     xyz
1        102     www

2        100     qqq
2        101     rrr
2        102     ttt

我有100个这样的u_a_id。我需要复制相同的内容,但要通过将u_a_id增加100十次,使总记录变为1000。

因此,输出将是:

u_a_id   c_id    c_val
1        100     abc
1        101     xyz
1        102     www

2        100     qqq
2        101     rrr
2        102     ttt

101      100     abc
101      101     xyz
101      102     www

102      100     qqq
102      101     rrr
102      102     ttt

有快速的方法吗?

4 个答案:

答案 0 :(得分:2)

我假设您希望数据集的u_a_id = 1扩展为101、201,最大为901。

使用WITH子句生成9个数字,然后乘以100。将其与原始表交叉连接以获取增加的集合:

insert into your_table
with cte as ( 
      select level * 100 as val
      from dual
      connect by level <= 9 )
select t.u_a_id + cte.val
       , t.c_id
       , t.c_val
from your_table t
     cross join cte

答案 1 :(得分:2)

您可以使用递归子查询分解子句:

Oracle设置

CREATE TABLE table_name ( u_a_id, c_id, c_val ) AS
  SELECT 1, 100, 'abc' FROM DUAL UNION ALL
  SELECT 1, 101, 'xyz' FROM DUAL UNION ALL
  SELECT 1, 102, 'www' FROM DUAL UNION ALL
  SELECT 2, 100, 'qqq' FROM DUAL UNION ALL
  SELECT 2, 101, 'rrr' FROM DUAL UNION ALL
  SELECT 2, 102, 'ttt' FROM DUAL

插入

INSERT INTO table_name ( u_a_id, c_id, c_val )
  WITH rsqfc ( u_a_id, c_id, c_val ) AS (
    SELECT u_a_id + 100, c_id, c_val
    FROM   table_name
  UNION ALL
    SELECT u_a_id + 100, c_id, c_val
    FROM   rsqfc
    WHERE  u_a_id < 1000
  )
  SELECT u_a_id, c_id, c_val
  FROM   rsqfc

输出

SELECT * FROM table_name
U_A_ID | C_ID | C_VAL
-----: | ---: | :----
     1 |  100 | abc  
     1 |  101 | xyz  
     1 |  102 | www  
     2 |  100 | qqq  
     2 |  101 | rrr  
     2 |  102 | ttt  
   101 |  100 | abc  
   101 |  101 | xyz  
   101 |  102 | www  
   102 |  100 | qqq  
   102 |  101 | rrr  
   102 |  102 | ttt  
   201 |  100 | abc  
   201 |  101 | xyz  
   201 |  102 | www  
   202 |  100 | qqq  
   202 |  101 | rrr  
   202 |  102 | ttt  
...
  1001 |  100 | abc  
  1001 |  101 | xyz  
  1001 |  102 | www  
  1002 |  100 | qqq  
  1002 |  101 | rrr  
  1002 |  102 | ttt  

db <>提琴here

答案 2 :(得分:1)

select中,您可以这样做:

select u_a_id, c_id, c_val
from t
union all
select u_a_id + 100, c_id, c_val
from t
where u_a_id in ( . . . )   -- your list here

或在表中插入行:

insert into t (u_a_id, c_id, c_val)
    select u_a_id + 100, c_id, c_val
    from t
    where u_a_id in ( . . . );   -- your list here

答案 3 :(得分:1)

类似这样的东西:

INSERT INTO table
  SELECT u_a_id +100 AS u_a_id, c_id, c_val
    FROM table
    WHERE u_a_id BETWEEN 1 AND 100

运行后,重新运行+ 200,+ 300等,而不是+100 ...