我有两张桌子,如下所示。 当 table_a.name=table_b.name 且 table_a.value=table_b.value 并且 table_b.id 未设置为其他 table_a.fid 时,我想将 table_a.fid 更新为 table_b.id
表_a(a):
id(int) name(varchar) value(varchar) fid(int)
1 name_a value_1 0
2 name_a value_1 0
3 name_a value_1 0
4 name_b value_2 0
5 name_c value_3 0
表_b (b):
id(int) name(varchar) value(varchar)
1 name_a value_1
2 name_a value_1
3 name_b value_2
4 name_b value_2
table_a预期结果:
id name value fid
1 name_a value_1 1 // b.id(1,2) matched, so set the first b.id(1) to a.fid(1)
2 name_a value_1 2 // b.id(1,2) matched and b.id(1) already set to a.fid(1), so set the second b.id(2) to a.fid(2)
3 name_a value_1 0 // b.id(1,2) matched and b.id(1,2) already set to a.fid(1,2), so is 0
4 name_b value_2 3 // b.id(3,4) matched. so set the first b.id(3) to a.fid
5 name_c value_3 0 // b not matched
如果您使用 mysql 8.0 或更高版本,那么您可以使用窗口函数
ROW_NUMBER()
为相关记录集中的行分配订单号,然后也使用此唯一标识符进行连接:
with cte_a as (
select *, row_number() over (partition by name, val order by id) as rn
from table_a
),
cte_b as (
select *, row_number() over (partition by name, val order by id) as rn
from table_b
)
select cte_a.id, cte_a.name, cte_a.val, coalesce(cte_b.id, 0) as fid
from cte_a
left join cte_b using(name, val, rn);
结果:
id name val fid
1 name_a value_1 1
2 name_a value_1 2
3 name_a value_1 0
4 name_b value_2 3
5 name_c value_3 0