SQL案例

一个sql更新案例,直接看图,数据有一层隐含逻辑 B1<=A1,D1<=C1
假设表头已经全部存在,现在就是要移动成目标的形式。

在数据库里面写好模拟数据,如下图:

实现SQL语句:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
update test join (select id, k, V1, V2, tempv3 as V3, tempv4 as v4 from (
select *,
if(@tempk=tmp.K, @tempv3,'') tempv3,
if(@tempk=tmp.K, @tempv4,'') tempv4,
@tempv3:=tmp.V1,
@tempv4:=tmp.V2,
@tempk:=tmp.K
from
(select * from test order by k, V1) tmp,
(select @tempk:=null,@tempv3:=null,@tempv4:=null) r
) ret where tempv3 != '') ttt
on test.id = ttt.id
set test.V3 = ttt.V3, test.V4 = ttt.V4
where test.id = ttt.id

SQL执行结果:

◀        
        ▶