我现在有两张表,表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字段 (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这条记录,我就需要把它删了..
我这里有几千条数据,想用程序改.
请各位朋友给点详细的解决办法,谢谢了
解决方案 »
- 请教键盘监听器的问题
- java中,什么是instance method 中文是什么?能否举例说明谢谢!
- java怎样写导航面板
- 在命令行中使用java命令产生的错误
- 如何在文本框中设置空串?急!!
- java菜菜菜提问一个大家见笑的问题!
- Runtime.getRuntime().exec()怎么样,可以执行JAR包里面的程序
- 如何在jdbtable中加入组合框(给50)
- <jsp:setProperty name="PageHeaderInfo" property="*" />是什么意思?
- Java文件在windows编译后的class,放到linux上运行乱码
- 如何设置JScrollPane 上下滚动 但是左右不滚动啊
- 急!急!急!!sql语句,取得年份月份
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)
for (Long id : idList1) {
if (!idList2.contains(id)) {
insert ID为id的这条记录插入到表2
}
}for (Long id : idList2) {
if (!idList1.contains(id)) {
从表2delete ID为id的这条记录
}
}
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
....拿到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)
insert into table1 select * from table2注2:上面子查询使用了左右关联,看上去复杂了些,但是当数据量庞大时,效率是not in的N倍.
后面集合较小时,使用In才有意义.
如果只是自己开发过程玩,两条SQL搞定。