现在有这样一个问题 
有一个 user 表 (id , email,superID)
另外一个表a (id)只有一个字段 
现在有很多的email是非空的重复的  还有些email是空的 现在要做的 是
1 把非空重复的email 的第一个id 插入到表a(id),这个表a 仅仅放有重复的email组的第一次出现那个email的id 
2 把非空重复的email组 的第一个id的所在记录 的 superID=本身的id 
  有重复email的其他id所在记录的 superID=该组第一个email的id例子如下 id , email,      superID
1
2      [email protected]
3      [email protected]
4      [email protected]
5      [email protected]
6      [email protected]针对上面的要求 得到如下
1这里需要把id=2  id=3  插入到表a 
2id , email,      superID
1
2      [email protected]     2
3      [email protected]      3
4      [email protected]     2 
5      [email protected]
6      [email protected]      3 
    这2个sql如何写?

解决方案 »

  1.   

    先来最简单的第2个insert into a select id from user where email <>'' group by email having count(email)>=2 order by id ;
      

  2.   

    1,
    insert into a select id from user u where 
    1<(select count(*) from user where email=u.email) and 
    not exists(select 1 from user where email=u.email and id<u.id);2,
    update user a,(select email,min(id) mid from user group by email
    having count(*)>1) b
    set a.superid=b.mid
    where a.email=b.email;

      

  3.   

     update user,(select id,email from user where email <>'' group by email having count(email)>=2) b set user.superid=b.id where user.email=b.email;