我现在有两张表,表1和表2 
表1字段 (x,y字段的内容我省了)  
id name x y 
1   一 
2   二 
3   三 
4   四 
5   五
表2字段 (m,n字段的内容我省了)
id name m n
1   一
2   二
4   四
5   五
6   六
就和上面两个表差不多,我现在要做的事情是写一个程序让表2的id 和name 与表1的id 和name对应
比如表2没有id为3这条记录,我就需要把表2里增加一条id为3 name为三的这么一条记录.
  表2里多了id为6这条记录,我就需要把它删了..
  我这里有几千条数据,想用程序改.
  
 请各位朋友给点详细的解决办法,谢谢了

解决方案 »

  1.   

    1、表2中增加没有的内容
    select id form 表1 where id not in(select id from 表2)
    拿出所有的id值,循环insert into 表2 (id) values (拿到的值)2、表2中删除多余的内容
    delete 表2 where id not in( select id from 表1)
      

  2.   

    表1的idList1 表2的idList2
    for (Long id : idList1) {
        if (!idList2.contains(id)) {
               insert ID为id的这条记录插入到表2
        }
    }for (Long id : idList2) {
        if (!idList1.contains(id)) {
               从表2delete ID为id的这条记录
        }
    }
      

  3.   

    上面insert delete要调用你自己的service方法
      

  4.   

    我记得和并表应该用view来做,不过忘了,你可以查一下view的做法,挺简单的
      

  5.   

    两条SQL语句搞定,写什么程序啊! 把问题复杂化了 !我大致给你写下思路,没测,家里机器没环境.第一条:删除第二张表没有的数据
    delete table2 where table2.id in (select table2.id from
      (select table2.id,table1.id form table2 left join table1 on table1.id=table2.id)  //子查询1
     where tabl1.id!=null)第二条:插入表一有而表二没有的
     insert table2(id,name) select id,name from table1 where table1.id in (select table1.id from
      (select table2.id,table1.id form table1 left join table2 on table1.id=table2.id)  //子查询2
     where tabl1.id!=null)
    若是Oracle更简单,直接将表一插入表二,连查都不用查,出现异常时不处理或回滚处理就行
    begin
      insert table2 select from table1
      exception null;  //有相同ID会否出异常,但是不处理.
    end
      

  6.   

    1、表2中增加没有的内容
    ....拿到JDBC connection的我就不写了...
    Statement sta1 = conn.createStatement();
    String insert = "insert into 表2 (id) values (?)";
    PreparedStatement ps = conn.PreparedStatement(insert);
    String sql = "select id form 表1 where id not in(select id from 表2)";
    ResultSet rs = sta1.excuteQuery(sql);
    while(rs.next){
     String id = rs.getNString("id");
     ps.set(1,id);
     ps.addBatch(); 
    }
    ps.executeBatch();
    ....异常,资源关闭什么的就不写了2、表2中删除多余的内容这条SQL语句就可以搞定了
    delete 表2 where id not in( select id from 表1)
      

  7.   

    注:每种数据库对于批量插入的SQL语法支持可能不同,大致这样.当然实在不行可以循环慢慢查吧!
    insert into table1 select * from table2注2:上面子查询使用了左右关联,看上去复杂了些,但是当数据量庞大时,效率是not in的N倍.
      后面集合较小时,使用In才有意义.
      

  8.   

    我郁闷..mysql不支持子查询.现在该怎么办呀
      

  9.   

    搞一存储过程直接干掉
    如果只是自己开发过程玩,两条SQL搞定。