数据库多表并查

  • 涉及多表并查的情况,我们先只讨论不用左右外连接等方式,而是通过结果集来取最后的数据。
select r.*, 
(select count(collector_id) from lj_garbagecollector where left(collector_id,length("330681117")+3) = r.region_id) as collector_num,
(select count(household_id) from lj_household where left(household_id,length("330681117")+3) = r.region_id) as household_num
from 
(select left(region_id,length("330681117")+3) as region_id, 
count(region_id) as region_num from lj_region where 
length(region_id) = 12 and 
left(region_id,length("330681117")) = "330681117"
group by left(region_id,length("330681117")+3)) r

拿这个sql举例,这个涉及三表查询,这三者之间的联系是互相的主键有关联。然后这边笔者把其中一个表作为底层结果集,然后限制好条件,其他的作为一个查询结果出现在该结果集外层的结果集当中。
当然,三表查询或者多表查询,如果涉及的数据量比较多,不建议采用多表查询的方式。应该要考虑到相关性能处理。这边笔者只是单纯作为一个sql来说,多表查询可以这么来取。
先把一个当做结果集,然后找表之间的联系。然后作为结果集出现在查询结果处。

发布了5 篇原创文章 · 获赞 6 · 访问量 1381

猜你喜欢

转载自blog.csdn.net/kaneandblanche/article/details/104860782