不知道查询时,可否实现将两个字段组合起来查询?
比如,有table1 和table2,两个的表的主键都是字段组合,比如table1的主键是a1、b1字段的组合,table2的主键是a2、b2的组合。我现在想查询table2中的a2、b2的组合除a1 、b1相同的其它记录。不知怎么写语句。如实例:
table1 table2
a1 b1 a2 b2dd ff dd ff
rr gg ee gg
pp kk pp gg我希望查询到的结果:
ee gg
pp gg
比如,有table1 和table2,两个的表的主键都是字段组合,比如table1的主键是a1、b1字段的组合,table2的主键是a2、b2的组合。我现在想查询table2中的a2、b2的组合除a1 、b1相同的其它记录。不知怎么写语句。如实例:
table1 table2
a1 b1 a2 b2dd ff dd ff
rr gg ee gg
pp kk pp gg我希望查询到的结果:
ee gg
pp gg
where not exists(select 1 from table1 b where a.a2=b.a1 and a.b2=b.b1
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 行)
*/
where not exists (
select 1 from table1
where a1=a.a2
and b1=a.b2
)
on b.a1=a.a2
and b.b1=a.b2
where b.a1 is null
select * from table2 where not exists(select * from table1 where a1=a2 and b1=b2)