具有特定条件的SQL更新查询

时间:2014-07-07 10:00:54

标签: sql oracle11g

我正在使用Oracle 11g数据库并有两个表:

EMP

ID  EMPNO   AGE DATE_PUBLISHED

1   1001    11  14/01/1999

2   1002    22  14/01/1999

3   1003    33  14/01/1999

4   1004    44  14/01/1999

5   1005    55  14/01/1999

6   1006    66  14/01/1999

EMP_MIRROR

ID  EMPNO   AGE DATE_PUBLISHED

1   1001    11  05/01/2004

2   1123    54  05/01/2004

3   1003    87  05/01/2004

4   1004    65  05/01/2004

5   1545    78  05/01/2004

6   1006    14  05/01/2004

我想根据以下条件更新DATE_PUBLISHED表的EMP_MIRROR列:

如果两个表中的任何IDEMPNOAGE的值不同,那么DATE_PUBLISHED的{​​{1}}列就会有所不同应更新为EMP_MIRROR

SYSDATE

EMP_MIRROR (after updation)

结果集的说明:

ID  EMPNO   AGE DATE_PUBLISHED

1   1001    11  05/01/2004

2   1123    54  07/07/2014

3   1003    87  07/07/2014

4   1004    65  07/07/2014

5   1545    78  07/07/2014

6   1006    14  07/07/2014

请建议一个可以达到此结果的查询。

4 个答案:

答案 0 :(得分:0)

此标准SQL解决方案(因为没有DBMS指定)将是:

UPDATE  EMP_MIRROR
SET     DATE_PUBLISHED = CURRENT_TIMESTAMP
WHERE   EXISTS
        (   SELECT  1 
            FROM    EMP
            WHERE   EMP.ID = EMP_MIRROR.ID
            AND (   EMP.AGE <> EMP_MIRROR.AGE
                OR  EMP.EMPNO <> EMP_MIRROR.EMPNO
                )
        );

<强> Example on SQL Fiddle

答案 1 :(得分:0)

UPDATE emp_mirror
SET    date_published = SYSDATE
WHERE EXISTS (SELECT 1
              FROM   emp
              WHERE  emp.id = emp_mirror.id
              AND  ((emp.age != emp_mirror.age OR)
                    (emp.empno != emp_mirror.empno)));

答案 2 :(得分:0)

with temp as(
select [ID]
       ,[DATE_PUBLISHED]

from [EMP_MIRROR]
inner join [EMP] on [EMP_MIRROR].[ID] = [EMP].[ID]

where [EMP_MIRROR].[DATE_PUBLISHED] <> [EMP].[DATE_PUBLISHED]
)

update [EMP_MIRROR] set [DATE_PUBLISHED] = GETDATE() where ID = (Select [ID] from temp)

这可能是一种更好的方法,但是如果您要比较两个表,然后选择日期不匹配的ID到临时表中,那么在新的列表中使用更新的ID。

仅供参考,我还没有检查过这个陈述是否有效,但是它的要点就在那里,当我有时间测试它时,我会更新它。

答案 3 :(得分:0)

可能是这样的东西

With CTE AS 
(
 SELECT EM.* FROM EMP_MIRROR EM JOIN EMP E ON E.ID = EM.ID
 WHERE EM.AGE <> E.AGE OR E.EMPNO <> EM.EMPNO 
)
Update EMP_MIRROR EE SET DATE_PUBLISHED = CURRENT_TIMESTAMP
FROM CTE JOIN EMP_MIRROR ON CTE.EMPNO = EE.EMPNO