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

一个语句怎么查询下一级是否存在数据?
TB1
id name
1 a
2 b
3 c

TB2
id tb1_id name
1 1 aa
2 1 aaa
3 3 cc


要查询出结果

TB1.id , TB1.name , TB2.count
1 a 2
2 b 0
3 c 1
------解决方案--------------------
selet TB1.id , TB1.name , sum(isnull(TB2.count),0)
from TB1 left join TB2 on TB1.id=TB2.id
------解决方案--------------------
select TB1.id,TB1.name,count(*) from TB1,TB2 where TB1.id=TB2.tb1_id group by TB1.id,TB1.name
------解决方案--------------------
create table TB1
(
ID INT,
name varchar(10)
)
create  table TB2
(
id int,
tb1_id int,
name varchar(10)
)
insert into  TB1 select 1,'a'
union all select 2 ,'b'
union all select 3,'c'

insert into TB2 select 1,1,'aa'
union all select 2,1,'aaa'
union all select 3,3,'cc'

select TB1.ID,TB1.name,count(TB2.tb1_id)as TB2_count FROM TB1 
LEFT JOIN TB2 ON TB1.ID=TB2.tb1_id 
group by tb1.ID,tb1.name
/*
ID name TB2_count
1 a 2
2 b 0
3 c 1
*/