利用子查询更新字段
作者:勇斌 | 分类: 大话技术 | 标签: 大话技术 | 日期:2008-02-29
今天在做数据更新时,打算将某个帖子下面的所有回复排定楼层,测试发现结果不对。
update sq_forum_reply s set floor = (
select row_number() over(partition by thread_id order by gmt_create)
from sq_forum_reply t
where s.id = t.id
and t.thread_id =20013990
and floor is null
) where thread_id=20013990 and floor is null;
查看执行计划发现,原因是子查询根据要更新的当前行的id去查询匹配记录,这样子查询每次只能查到一条记录,所以排序始终等于1。
修改语句后:
update sq_forum_reply s set floor = (
select rn from (
select id,row_number() over(partition by thread_id order by gmt_create) rn
from sq_forum_reply t
where t.thread_id = 20013990 and floor is null
) where s.id = id
) where thread_id=20013990 and floor is null ;
sql> select id,floor from sq_forum_reply where thread_id=20013990;
ID FLOOR
———- ———-
20004120 1
20004121 2
20004122 3
所以在写这类sql时,一定要确保子查询的结果集和要更新的结果集一致。



最近也是做到了一个子查询更新,不过略有不同
更新T1表C1字段的值,C1字段里有N个值,C1字段的值对应的T2表的C1字段的值,需要把T1.C1里字段的各个值按照T2表的对应关系更新。Mysql下
diefish @ March 5, 2008 |
UTF8字符集下如何做数据订正b( ̄▽ ̄)d(─.─||)
环形变压器 @ December 21, 2009 |