A表字段(区县表)
QuXianId QuXianName
1 宝山
2 长宁
3 宗明
4 徐汇
... ...
19 上海周边
B表字段,和A表中相同的QuXianId字段(景点表吧)
Guid QuXianId Title Desc
1 4 万体馆 八万人体育馆
2 1 宝山 。。。
两个表联合
QuXianId Num
1 0
2 0
3 0
...
19 0
统计出所有区的景点 数量
疑惑:1.表B中如果没有A中QuXianId值,如何显示为0?
select QuXian_id,num=count(*) from word_data where QuXian_id =10
group by quxian_id
然后循环查询出所有,明显的性能问题。
不知道有其他更好的方法,请大家指点,谢谢。
为什么要循环?
select QuXian_ID, Count(1) as TopCount from B
--where B. QuXian_ID in (Select QuXian_ID from A) B的ID肯定在A,反之未必
group by QuXian_ID
union all
select QuXian_ID,0 as TopCount from A where A.QuXian_ID not in (Select distinct QuXian_ID from B)
order by TopCount desc
这个查询有问题?你给些测试数据。
可以这样写的哦,先对B表做统计,然后再与A表关联出结果。你试试
select QuXianId,isnull(b.num,0) as num from 区县表 a
left join
(
select QuXianId,count(*) as num from 景点表
group by QuXianId
) b on a.QuXianId=b.QuXianId