如何用另一个表中的值更新表中的所有记录,其中记录按id匹配



假设我有两个表:

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 |
+-------------+----+-------------------+
|         ... | ...|               ... |
+-------------+----+-------------------+

现在我想在USER表中填写CREATE_TIMESTAMP列,从REFERENCE_CREATED_TIMESTAMPS表中获取值,即对于ID=2的用户,我将使用CREATED_TIMESTAMP的值从REFERENCE_CREATED_TIMESTAMPS行中获取TABLE_NAME=USERID=2

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

试试…

Update UserTable Set CREATED_TIMESTAMP=
(Select Min(CREATED_TIMESTAMP) from REFERENCE_CREATED_TIMESTAMPS where
 REFERENCE_CREATED_TIMESTAMPS.Id=UserTable.Id and Table_Name='User')
update  "User"
set     CREATED_TIMESTAMP =
        (
        select  rct.CREATED_TIMESTAMP
        from    REFERENCE_CREATED_TIMESTAMPS rct
        where   rct.ID = "User".ID
                and rct.TABLE_NAME = 'USER'
        );

像这样:

  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;

相关内容

  • 没有找到相关文章

最新更新