日期:2014-05-17  浏览次数:20676 次

请问一个复杂的sql
我有两张表A,B,A表的数据有很多重复的人,如下
pid name phone
P421 小王 13881231
P187 小李 13498798
J986 小张 15812931
J823 小王 13881231
P283 小张 15812931
J180 小李 13498798
......

还有一张关联表B
linkid pid orgid
1 P421 o122
2 P187 o124
3 J986 o123
4 J180 o231
5 283 o871
6 J823 o281
......

我想要删除A表中的所有重复的人的数据,以P开头的为准,同时替换B中,被删除的数据的同名的pid。
请问哪位高手,帮我写个sql,批量修改,数据量实在有点大。

------解决方案--------------------
写个存储过程比较好点吧,一个sql语句,可能写出来不是太好理解。
------解决方案--------------------
delete from A where not exists(select 1 from A where rowid=(select max(rowid) from A where pid like 'P%' group by pid) and pid like 'P%'
删除大概可以这样吧??
还得你自己写吧,别人没有你的数据,写出来也可能会出错,自己可以联系下。
更新B表。没明白啥意思
------解决方案--------------------
数据量比较大,考虑效率可以用rowid处理
先删除b中的数据
SQL code

delete from b where exists(select pid from a where exists(select 1 from (select min(rowid) 
rowid,name from a group by name) z where z.name=a.name and z.rowid<a.rowid) and a.pid=b.pid );