mysql中表的合并问题
问题描述:
A表 处理一下放进B表
处理如下
以a和b列 去重
a和b相同的数据 取c列最小值 c列相同 取 id小的 或者随机取
答
分析一下
1、以a和b列 去重
这个就是简单的group by a,b 两个列就行了
2 a和b相同的数据 取c列最小值
这个就是取c的最小值
min(c)
3 c列相同 取 id小的 或者随机取
只能用子查询了
select a,b,min(c),(select id from tableA TB where ta.a=TB.a and TA.b=TB.b and TA.c=TB.c limit 1) id from TableA TA group by a,b
这个limit 1是随机的, 如果select min(id) 就是最小值。
答
insert into B表
select *
from A表 t
where not exists (select 1 from A表 where a=t.a and b=t.b and (c<t.c or c=t.c and id<t.id)