日期:2014-05-18 浏览次数:20601 次
--> 测试数据:[A1]
if object_id('[A1]') is not null drop table [A1]
create table [A1]([aid] int,[acontent] varchar(6))
insert [A1]
select 1,'aaaaaa' union all
select 2,'bbbbbb' union all
select 3,'cccccc' union all
select 4,'dddddd' union all
select 5,'eeeeee'
--> 测试数据:[B2]
if object_id('[B2]') is not null drop table [B2]
create table [B2]([bid] int,[aid] int,[bcontent] varchar(7))
insert [B2]
select 1,1,'aaaaaaa' union all
select 2,1,'aaaaaaa' union all
select 3,1,'aaaaaaa' union all
select 4,2,'aaaaaaa' union all
select 5,2,'aaaaaaa' union all
select 6,3,'aaaaaaa' union all
select 7,3,'aaaaaaa'
select 
    a.aid,
    ISNULL(COUNT(b.aid),0) as baid 
from 
    A1 a 
left join 
    B2 b 
on 
    a.aid=b.aid
group by 
    a.aid
/*
aid    baid
---------------
1    3
2    2
3    2
4    0
5    0
*/
------解决方案--------------------
SELECT a.aid,baid=(SELECT COUNT(*) FROM B2 b WHERE a.aid=b.aid) FROM A1 a