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

字段组合的查询
不知道查询时,可否实现将两个字段组合起来查询?
比如,有table1   和table2,两个的表的主键都是字段组合,比如table1的主键是a1、b1字段的组合,table2的主键是a2、b2的组合。我现在想查询table2中的a2、b2的组合除a1   、b1相同的其它记录。不知怎么写语句。如实例:
table1                                 table2
a1     b1                                 a2       b2

dd     ff                                 dd       ff
rr     gg                                 ee       gg
pp     kk                                 pp       gg

我希望查询到的结果:
ee     gg
pp     gg




------解决方案--------------------
select * from table2 a
where not exists(select 1 from table1 b where a.a2=b.a1 and a.b2=b.b1
------解决方案--------------------
select * from table2 where a2 <> a1 and b2 <> b1
------解决方案--------------------
drop table table1,table2
go
create table table1(a1 varchar(10),b1 varchar(10))
insert into table1
select 'dd ', 'ff '
union all select 'rr ', 'gg '
union all select 'pp ', 'kk '
create table table2(a2 varchar(10),b2 varchar(10))
insert into table2
select 'dd ', 'ff '
union all select 'ee ', 'gg '
union all select 'pp ', 'gg '

select * from table2 a
where not exists(select 1 from table1 b where a.a2=b.a1 and a.b2=b.b1)
/*
a2 b2
---------- ----------
ee gg
pp gg

(所影响的行数为 2 行)
*/
------解决方案--------------------
select * from table2 a
where not exists (
select 1 from table1
where a1=a.a2
and b1=a.b2
)

------解决方案--------------------
or:

select a.* from table2 a left join table1 b
on b.a1=a.a2
and b.b1=a.b2
where b.a1 is null


------解决方案--------------------
---try---
select * from table2 where not exists(select * from table1 where a1=a2 and b1=b2)
------解决方案--------------------
同意樓上