将列从一个表复制到另一个表table1.col = table2.col

时间:2014-04-29 13:31:30

标签: sql db2

假设有两个表具有insert查询中提到的数据。两个表之间没有外键引用。

create table uref.slave (
SLAVE_ID SMALLINT NOT NULL PRIMARY KEY,
DESC VARCHAR(20) 
);

INSERT INTO uref.SLAVE values (1, null)
INSERT INTO uref.SLAVE values (2, null)


create table uref.master (
MASTER_ID SMALLINT NOT NULL PRIMARY KEY,
SLAVE_ID SMALLINT,
DESC VARCHAR(20) 
);

INSERT INTO uref.MASTER values (1,1,'value1')
INSERT INTO uref.MASTER values (2,2,'value2')

现在我需要一个查询,根据uref.master.DESCuref.slave.DESC复制到uref.master.SLAVE_ID = uref.slave.SLAVE_ID

3 个答案:

答案 0 :(得分:1)

UPDATE uref.SLAVE t1
    SET Desc = 
    (
        SELECT t2.Desc
        FROM uref.MASTER  t2
        WHERE t1.SLAVE_ID = t2.SLAVE_ID
    )
    WHERE EXISTS 
    ( 
        SELECT * 
        FROM uref.MASTER t2
        WHERE t1.SLAVE_ID = t2.SLAVE_ID
        AND NOT t1.Desc=t2.Desc
    )  
    AND t1.Desc IS NULL

答案 1 :(得分:1)

最简单的解决方案可能是使用MERGE

MERGE INTO uref.SLAVE s
  USING uref.MASTER m
  ON (s.SLAVE_ID = m.SLAVE_ID)
  WHEN MATCHED 
  THEN UPDATE SET Desc = m.Desc

只有在需要进行更改时才可以进行更新

MERGE INTO uref.SLAVE s
  USING uref.MASTER m
  ON (s.SLAVE_ID = m.SLAVE_ID)
  WHEN MATCHED
   and (   s.Desc <> m.Desc
       or (s.Desc is null and m.Desc is not null)
       ) 
  THEN UPDATE SET Desc = m.Desc

答案 2 :(得分:0)

如果是sql server,请尝试以下sql :(重新检查表名和字段)

declare @urefSlave table (
SLAVE_ID SMALLINT ,
[DESC] VARCHAR(20) 
);

INSERT INTO @urefSlave values (1, null)
INSERT INTO @urefSlave values (2, null)


Declare @urefMaster table (
MASTER_ID SMALLINT,
SLAVE_ID SMALLINT,
[DESC] VARCHAR(20) 
);

INSERT INTO @urefMaster values (1,1,'value1')
INSERT INTO @urefMaster values (2,2,'value2')

select * from @urefMaster
select * from @urefSlave

update @urefSlave 
set [DESC] = b.[DESC]
from @urefSlave a inner join @urefMaster  b on a.SLAVE_ID = b.SLAVE_ID

select * from @urefSlave

结果:

MASTER_ID SLAVE_ID DESC
--------- -------- --------------------
1         1        value1
2         2        value2



SLAVE_ID DESC
-------- --------------------
1        value1
2        value2

<强>更新

在db2中帮不了多少,因为我没有运行语法的工具 但是从这个链接db2 update help

您可以修改其中的示例以满足您的要求:

UPDATE EMPLOYEE EU
     SET (EU.SALARY, EU.COMM)
     =
   (SELECT AVG(ES.SALARY), AVG(ES.COMM)
     FROM EMPLOYEE ES
     WHERE ES.WORKDEPT = EU.WORKDEPT)
     WHERE EU.EMPNO = '000120' 

希望得到这个帮助。