如果主表

时间:2016-03-04 13:46:30

标签: sql sql-server oracle dml

我有两张表,如下所述

表1包含密钥

| key  |  
| k1   |
| k2   | 
| k3   | 

表2包含密钥与资源

的映射
  | res  |   key    |
  | r1   | k1       |
  | r1   | k2       |
  | r2   | k1       |

最终目标是在table2中为每个密钥配置每个资源的映射。 由于table2不完整,所以我需要插入不存在的映射。

那么如何找出tale2中缺少哪个资源 - 键映射 然后将它们插入table2

如表2中缺少以下键

| res| key  |  
| r1 | k3   |
| r2 | k2   | 
| r2 | k3   | 

所以最后table2看起来如下所示。

  | res  |   key    |
  | r1   | k1       |
  | r1   | k2       |
  | r1   | k3       |
  | r2   | k1       |
  | r2   | k2       |
  | r2   | k3       |

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

我会质疑表格中是否存在每种组合的必要性,因为这意味着表格要么不存储相关数据(即,如果每种组合都存在,那么你可以假设并且不要我需要把它放到一个表中)或者有一些你没有显示的列,你将把这些列放入你的表中,这些列为NULL"占位符",这是添加了一堆"非数据"到数据库。

无论如何,这应该做你需要的:

INSERT INTO Table_2 (resource, key)
SELECT
    R.resource,
    T1.key
FROM
    Resources R
CROSS JOIN Table_1 T1
WHERE
    NOT EXISTS
    (
        SELECT *
        FROM Table_2 T2
        WHERE
            T2.resource = R.resource AND
            T2.key = T1.key
    )

答案 1 :(得分:0)

Partition outer join加上空行的过滤器来救援!

with t1 as (select 1 id, 'k1' key from dual union all
            select 2 id, 'k2' key from dual union all
            select 3 id, 'k3' key from dual),
     t2 as (select 1 id, 'r1' res, 'k1' key from dual union all
            select 2 id, 'r1' res, 'k2' key from dual union all
            select 3 id, 'r2' res, 'k1' key from dual)
-- end of mimicking tables t1 and t2 with your data in them. You would not need these subqueries.
-- Run the sql below, substituting in your table names as appropriate.
select t2.res,
       t1.key
from   t1
       left outer join t2 partition by (t2.res) on (t1.key = t2.key)
where  t2.id is null;

RES KEY
--- ---
r1  k3 
r2  k2 
r2  k3 

至于您在缺失行中添加的额外要求,它就像:

一样简单
insert into t2 (id, res, key)
select t2_seq.nextval,
       t2.res,
       t1.key
from   t1
       left outer join t2 partition by (t2.res) on (t1.key = t2.key)
where  t2.id is null;

这假设您有一个序列填充表t2的id列。