假设我有两个表:
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=USER
和ID=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;