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

两表的storeid,productid的数据对比,并插入补全。

表tab1字段及数据示例如下:
storeid    productid
 001          021
 003          021
 002          094
 002          021
 001          094

表bill字段及数据示例如下:
id   storeid     productid     account
1     001          021           2
2     001          088           3
3     003          021           2
4     002          094           3
5     002          021           8
6     001          094           7
7     005          094           7
8     001          094           7


ms sql2000中,写一个SQL语句,两表数据对比,将在bill中存在的storeid,productid的数据,但在tab1中不存在的数据插入到tab1中。
例如上面的数据,运行SQL后,将下面的数据插入到tab1表中。
 001          088
 005          094
要实现这个,SQL怎么写呢?

------解决方案--------------------
insert into tab1(storeid,productid )
select storeid,productid
from bill a
where not exists(select 1 from tab1 b where a.storeid=b.storeid and a.productid=b.productid)


------解决方案--------------------
insert into tab1 (storeid,productid)
select distinct storeid,productid from bill a 
where not exists(select * from tab1 b where a.storeid=b.storeid and a.productid=b.productid)
------解决方案--------------------

insert into table1
select t.* from
(
select storeid,productid from bill
except
select storeid,productid from table1
)t