日期:2014-05-19  浏览次数:20403 次

求sql,比较简单的
两个表有相同的主键   都是3个
b1
p1   p2   p3   c4   c5
1     1     1     4     5
1     2     2     4     5
1     2     3     4     5
1     2     4     4     5

b2
p1   p2   p3   c4
1     1     1     4  
1     2     4     4  

想从b1中select出b2里面没有的主键所在的行,
b3
1     2     2     4     5
1     2     3     4     5

用not   in也行,不过最好不用,谢谢

------解决方案--------------------
drop table b1,b2
go
create table b1(p1 int,p2 int,p3 int,c4 int,c5 int)
insert into b1
select 1,1,1,4,5
union all select 1,2,2,4,5
union all select 1,2,3,4,5
union all select 1,2,4,4,5

create table b2(p1 int,p2 int,p3 int,c4 int)
insert into b2
select 1,1,1,4
union all select 1,2,4,4

select * from b1
where not exists(select 1 from b2 where b1.p1=b2.p1 and b1.p2=b2.p2 and b1.p3=b2.p3)

/*
p1 p2 p3 c4 c5
----------- ----------- ----------- ----------- -----------
1 2 2 4 5
1 2 3 4 5

(所影响的行数为 2 行)
*/
------解决方案--------------------
select 1 from b2 where b1.p1=b2.p1 and b1.p2=b2.p2 and b1.p3=b2.p3
为什么是select 1 呢?能说说么
----
和select * 是一个道理,但是返回的东西就是1,当然消耗的资源就少了