t1
id name
t2
id code
t3
id code fullname time
条件:t1.id = t2.id , t2.code = t3.code;
且t3的code的值是可重复的,需要根据time取最新值;
目的:把t3.fullname 的值赋给 t1.name
我自己写了个语句,但是不知道哪里错了?
update (select t1.name, t3.fullname
from t1, t2, t3
where t1.id = t2.id and t2.code = t3.code
and not exists(select 1 from t3 b where b.code = t3.code and b.time > t3.time))
set t1.name = t3.fullname
试了很多方法都不行,总会出一些问题,一般是因为关联的条件不是unique index/primary key,或者语法本身就有问题。
(我提问中那个方法就是由于关联条件不是唯一键值才出错的)
最后我自己搞出了这个方法,供有相同问题的同学参考
update t1 A set A.name=
(select C.fullname
from t2 B, (select * from t3 x
where x.time is not null
and not exists where (select 1 from t3 y where y.code = x.code and y.time > x.time
) C
where B.id = A.id and C.code = B.code
)
where exists
(select 1
from t2 B, (select * from t3 x
where x.time is not null
and not exists where (select 1 from t3 y where y.code = x.code and y.time > x.time
) C
where B.id = A.id and C.code = B.code
)
UPDATE t1,
t2,
t3
SET t1.name
= t3.fullname
WHERE
t1.id
= t2.id
AND t2.code
= t3.code
AND t3.time = (SELECT max(time) FROM t3)