请教一句sql语句:
tableA
序号 值
---------
1 AA
2 BB
3 CC
4 2
5 1
--------
我想变成的结果是下面这样子,也就是说4和5根据值字段的数去拿序号1和2的值来update自己,这个update语句要怎么写呢?
tableA
序号 值
---------
1 AA
2 BB
3 CC
4 BB
5 AA
自已看吧,我写了个示例
我已经测试成功了,关键点就是自连接
drop table tb
create table tb (
序号 int,
值 varchar(10)
)
insert tb
select 1,'AA' union all
select 2,'BB' union all
select 3,'CC' union all
select 4,'2' union all
select 5,'1'
select *
from tb
update a
set a.值=b.值
from tb a left join tb b on (a.值=rtrim(cast(b.序号 as varchar)))
where b.序号 is not null
select *
from tb
select tablea.序号,t.值 from tablea left join tablea t on tablea.序号=t.值
update _table set _value=(select top 1 _value from _table as a where a.number=_value)
序号:ID,值:NAME
用的是sqlite数据库,没有top 1
update tableA set NAME=
(select bNAME from (select a.ID as aID, b.NAME as bNAME from tableA a left join tableA b on a.NAME=b.ID where b.NAME<>'' )
where aID = ID)where ID in (select a.ID as aID from tableA a left join tableA b on a.NAME=b.ID where b.NAME<>'' )