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

结合其它表来查询的查询语句
表A的结构

id   bxgsid
1     2
2     2
3     1
4     3

表B的结构

id   aid

1     1
2     3
3     2
4     2

其中B.aid 和  A.id 是对应的
现在想用一句SQL语句,查询表B中,A.bxgsid=2的数据, 即结果应该为B.1 B.3 B.4

请指教,我现在写的是

select * from b where(select * from a where bxgsid=2)
但通不过,
------解决方案--------------------
select B.* from A,B where A.ID=B.ID and A.bxgsid=2

------解决方案--------------------
select * from b where sid in (select id from a where bxgsid=2)
------解决方案--------------------
----------------------------
-- Author  :TravyLee(物是人非事事休,欲语泪先流!)
-- Date    :2012-11-28 09:09:40
-- Version:

--      Microsoft SQL Server 2012 - 11.0.2100.60 (Intel X86) 

-- Feb 10 2012 19:13:17 

-- Copyright (c) Microsoft Corporation

-- Enterprise Edition: Core-based Licensing on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)

--
----------------------------
--> 测试数据:[A]
if object_id('[A]') is not null drop table [A]
go 
create table [A]([id] int,[bxgsid] int)
insert [A]
select 1,2 union all
select 2,2 union all
select 3,1 union all
select 4,3
--> 测试数据:[B]
if object_id('[B]') is not null drop table [B]
go 
create table [B]([id] int,[aid] int)
insert [B]
select 1,1 union all
select 2,3 union all
select 3,2 union all
select 4,2
go

select
b.*
from
B
inner join
A
on a.id=b.aid
where
a.bxgsid=2
/*
id aid
----------------
1 1
3 2
4 2
*/