假设二张表,如下:
表A:
ID,列1,列2
1 a 1
2 b 1
4 c 0
6 f 0
7 g 1
表B:
列1,列2
a 1
c 0我想要的结果是:当表B和表A的数据都匹配的情况下,读出表A的数据.
例: 根据表B的数据,得出表A的结果为:
ID,列1,列2
1 a 1
4 c 0
再说一下:
我不是要这样的:select ID,列1,列2 from 表A,表B where 表A.列1=表B.列1 and 表A.列2=表B.列2我是要这样: select ID,列1,列2 from 表A where (?),我要的是后面的where条件.谢谢!
表A:
ID,列1,列2
1 a 1
2 b 1
4 c 0
6 f 0
7 g 1
表B:
列1,列2
a 1
c 0我想要的结果是:当表B和表A的数据都匹配的情况下,读出表A的数据.
例: 根据表B的数据,得出表A的结果为:
ID,列1,列2
1 a 1
4 c 0
再说一下:
我不是要这样的:select ID,列1,列2 from 表A,表B where 表A.列1=表B.列1 and 表A.列2=表B.列2我是要这样: select ID,列1,列2 from 表A where (?),我要的是后面的where条件.谢谢!
if object_id('tempdb.dbo.#表A') is not null drop table #表A
create table #表A (ID int,列1 varchar(1),列2 int)
insert into #表A
select 1,'a',1 union all
select 2,'b',1 union all
select 4,'c',0 union all
select 6,'f',0 union all
select 7,'g',1
--> 测试数据: #表B
if object_id('tempdb.dbo.#表B') is not null drop table #表B
create table #表B (列1 varchar(1),列2 int)
insert into #表B
select 'a',1 union all
select 'c',0
goselect ID,列1,列2 from #表A a where exists(select * from #表B where 列1=a.列1 and 列2=a.列2)go
drop table #表A,#表B/*ID 列1 列2
----------- ---- -----------
1 a 1
4 c 0(所影响的行数为 2 行)
*/
select a.* from 表a a left join 表b b on a.id=b.id
and b.id is not null--or
select * from 表a a where exists(select 1 from 表b where id=a.id)--or
select * from 表a a where id in(select id from 表b)--等等
表A.列2 in (select 表B.列2 from 表B where 表A.列1=表B.列1)
--哦看错,表b没有id列的,那就换成列1吧:
select a.* from 表a a,表b b where a.列1=b.列1--or
select a.* from 表a a left join 表b b on a.列1=b.列1
and b.列1 is not null--or
select * from 表a a where exists(select 1 from 表b where 列1=a.列1)--or
select * from 表a a where 列1 in(select 列1 from 表b)--等等