table1
姓名 年级 专业 体重 身高 序号
刘德华 2 数控 65 175 1
周杰伦 1 音乐 55 172 2
刘涛 1 表演 46 165 3
王心玲 2 音乐 45 160 4table2
姓名 年级 专业 体重 身高 序号
刘德华 2 数控 65 175 1
周杰伦 3 广告涉及 55 172 2
盖茨 4 计算机 56 180 3
----------------------
其中姓名和年级为合成主键,怎样用sql 实现在table1 中插入 table2的记录,得到如下结果,只插入table1中不重复的记录
table1
姓名 年级 专业 体重 身高 序号
刘德华 2 数控 65 175 1
周杰伦 1 音乐 55 172 2
周杰伦 3 广告涉及 55 172 2
刘涛 1 表演 46 165 3
王心玲 2 音乐 45 160 4
盖茨 4 计算机 56 180 3
姓名 年级 专业 体重 身高 序号
刘德华 2 数控 65 175 1
周杰伦 1 音乐 55 172 2
刘涛 1 表演 46 165 3
王心玲 2 音乐 45 160 4table2
姓名 年级 专业 体重 身高 序号
刘德华 2 数控 65 175 1
周杰伦 3 广告涉及 55 172 2
盖茨 4 计算机 56 180 3
----------------------
其中姓名和年级为合成主键,怎样用sql 实现在table1 中插入 table2的记录,得到如下结果,只插入table1中不重复的记录
table1
姓名 年级 专业 体重 身高 序号
刘德华 2 数控 65 175 1
周杰伦 1 音乐 55 172 2
周杰伦 3 广告涉及 55 172 2
刘涛 1 表演 46 165 3
王心玲 2 音乐 45 160 4
盖茨 4 计算机 56 180 3
select distinct * into final_table
from
(
select * from table1
union all
select * from table2
)a
我能想到的方法只有用游标了,从table2中拣出一条记录,然后查看table1中有没有相同的,没有就插入。
也可以先insert from select,然后逐条检查table1中的记录,发现除本记录外还有其他记录与本记录相同((select count(*) from table1 where 姓名=..,年级=......) > 1)就删除本记录。
SELECT * FROM table2
WHERE NOT EXISTS (SELECT * FORM table2 A WHERE A.姓名 + CAST(年级 AS VRCHAR) IN(SELECT 姓名 + CAST(年级 AS VRCHAR) FROM table1 ))
因为select into语句需要目标表不存在才可以。
select distinct * into final_table
from
(
select * from table1
union all
select * from table2
)a
/
delete from table1
/
insert into table1
select * from final_table
/
drop final_table依次执行这4句应该可以
INSERT INTO table1 (select * from 不一致的结果集合)参考5楼
INSERT INTO table1
SELECT * FROM table2
WHERE NOT EXISTS (SELECT * FORM table2 A WHERE A.姓名 + CAST(年级 AS VRCHAR) IN(SELECT 姓名 + CAST(年级 AS VRCHAR) FROM table1 )) 或者自己写
不一致的结果集合
from
(
select * from table1
union all
select * from table2
)a 这个方法要搬动数据啊,数量量大的话相关只有两个表,添加纪律到table1中,如果table1中不存在table1中的记录
相关只有两个表,添加记录到table1中,如果table1中不存在table2中的记录
select src.* from table2 src where (src.姓名 + src.年级) not in (select dest.姓名 + dest.年级 from table1 dest)
)
语法上可能有错误,自己调整。
select distinct * into final_table
from
(
select * from table1
union all
select * from table2
)a
/
//delete from table1
/ SQLSERVER数据库用Trunc table table1 代替delete 会效率高些insert into table1
select * from final_table
/
drop final_table 依次执行这4句应该可以
INSERT INTO table1
(
select 姓名 , 年级 , 专业 , 体重 , 身高 ,序号
from Table2
except
select 姓名 , 年级 , 专业 , 体重 , 身高 , 序号
from Table1
)
------------------------------------------------------------------------
不一致的结果集合:INSERT INTO table1 (
select src.* from table2 src where (src.姓名 + src.年级) not in (select dest.姓名 + dest.年级 from table1 dest)
)语法上可能有错误,自己调整。------------------------------------------------INSERT INTO table1
(
select 姓名 , 年级 , 专业 , 体重 , 身高 ,序号
from Table2
except
select 姓名 , 年级 , 专业 , 体重 , 身高 , 序号
from Table1
)
结了结了,,多谢各位了,,总结这两个比较好!