需求:
加入现在有两个临时表
表一:
表二:
现在我们需求把表二的tag_3更新到表一. 根据tag_1 和 tag_2来更新. tag1+tag2相当于key值,但是这个key值不是唯一,但是tag3是不同的。所以常规的update 可以会出现第一列和第二列的tag3都更新为c或者d.
解决:
思路:
因为每组没有唯一的key值,所以我们可以考虑给每组每行添加一个唯一的key值,这个唯一key值是先分组然后每组从1开始递增。然后用分组的条件+地址的数组就组成了两个表可以关联的唯一key值。
分组序号可以参考下面的sql
select @i:=case when @type=a.name then @i+1 else 1 end as rownum,
@type:=a.name as name, a.id
from city a, (select @i:=0, @type:='') b
order by a.name
最后的完整sql
drop TEMPORARY table if EXISTS temp_a ;
CREATE TEMPORARY table temp_a(
tag_1 varchar(10) null,
tag_2 varchar(10) null,
tag_3 varchar(10) null
);
drop TEMPORARY table if EXISTS temp_a_1 ;
CREATE TEMPORARY table temp_a_1(
oid int not null,
tag varchar(10) null,
tag_1 varchar(10) null,
tag_2 varchar(10) null,
tag_3 varchar(10) null
);
drop TEMPORARY table if EXISTS temp_b ;
CREATE TEMPORARY table temp_b(
tag_1 varchar(10) null,
tag_2 varchar(10) null,
tag_3 varchar(10) null
);
drop TEMPORARY table if EXISTS temp_b_1 ;
CREATE TEMPORARY table temp_b_1(
oid int not null,
tag varchar(10) null,
tag_1 varchar(10) null,
tag_2 varchar(10) null,
tag_3 varchar(10) null
);
insert into temp_a(tag_1,tag_2)values ( 'a', 'b');
insert into temp_a(tag_1,tag_2) values ( 'a', 'b');
insert into temp_a(tag_1,tag_2)values ( 'w', 'e');
insert into temp_a(tag_1,tag_2) values ( 'w', 'e');
insert into temp_b(tag_1,tag_2,tag_3)VALUES("a", "b","c");
insert into temp_b(tag_1,tag_2,tag_3)VALUES("a", "b", "d");
insert into temp_b(tag_1,tag_2,tag_3)VALUES("w", "e","c");
insert into temp_b(tag_1,tag_2,tag_3)VALUES("w", "e", "d");
insert into temp_a_1(oid, tag, tag_1,tag_2)
select (@i:=case when @type=CONCAT(a.tag_1,a.tag_2) then @i+1 else 1 end),
@type:=CONCAT(a.tag_1,a.tag_2), a.tag_1, a.tag_2
from temp_a a, (select @i:=0, @type:='') b
order by a.tag_1, a.tag_2;
insert into temp_b_1(oid, tag, tag_1,tag_2, tag_3)
select (@i:=case when @type=CONCAT(a.tag_1,a.tag_2) then @i+1 else 1 end),
@type:=CONCAT(a.tag_1,a.tag_2), a.tag_1, a.tag_2, a.tag_3
from temp_b a, (select @i:=0, @type:='') b
order by a.tag_1, a.tag_2;
update temp_a_1 a
inner join temp_b_1 b
on a.tag_1 = b.tag_1
and a.tag_2 = b.tag_2
and a.oid = b.oid
set a.tag_3 = b.tag_3;
select * from temp_a_1;
select * from temp_b_1;