如何更新表中的所有记录,其中包含记录与id匹配的另一个表中的值?

时间:2013-06-17 16:34:07

标签: sql oracle batch-updates

假设我有两个表:

USER
+------+------+-------------------+
|   ID | NAME | CREATED_TIMESTAMP |
+------+------+-------------------+
|    1 |   N1 |              Null |
+------+------+-------------------+
|    2 |   N2 |              Null | <--------- acceptor of reference-value
+------+------+-------------------+           \
|  ... |  ... |               ... |            \
+------+------+-------------------+             \
                                                 \ 
REFERENCE_CREATED_TIMESTAMPS                      \
+-------------+----+-------------------+            these records match
|  TABLE_NAME | ID |CREATED_TIMESTAMP  |          /
+-------------+----+-------------------+         /
|        USER |  1 | 12.03.12 17:20:40 |        /
+-------------+----+-------------------+       /
|        USER |  2 | 14.03.12 10:12:54 |  <--- reference-value
+-------------+----+-------------------+
|   FOO_TABLE |  1 | 17.05.12 08:10:01 |
+-------------+----+-------------------+
|         ... | ...|               ... |
+-------------+----+-------------------+

现在我想用REFERENCE_CREATED_TIMESTAMPS表中的值来填充USER表中的CREATE_TIMESTAMP列,即对于ID = 2的用户,我将使用来自CREATED_TIMESTAMP行的值REFERENCE_CREATED_TIMESTAMPS其中TABLE_NAME=USERID=2

对USER表的所有记录执行此操作的查询是什么?

3 个答案:

答案 0 :(得分:4)

试试这个..

Update UserTable Set CREATED_TIMESTAMP=
(Select Min(CREATED_TIMESTAMP) from REFERENCE_CREATED_TIMESTAMPS where
 REFERENCE_CREATED_TIMESTAMPS.Id=UserTable.Id and Table_Name='User')

答案 1 :(得分:1)

update  "User"
set     CREATED_TIMESTAMP =
        (
        select  rct.CREATED_TIMESTAMP
        from    REFERENCE_CREATED_TIMESTAMPS rct
        where   rct.ID = "User".ID
                and rct.TABLE_NAME = 'USER'
        );

Example at SQL Fiddle.

答案 2 :(得分:0)

这样的事情:

  update USER u, REFERENCE_CREATED_TIMESTAMPS r
  set u.CREATED_TIMESTAMP = b.CREATED_TIMESTAMP
  where u.ID = r.ID AND r.TABLE_NAME = 'USER'
        AND u.ID = 2;