查询两张表中关联到的数据的和

需要查询出A和B表有 id 关联字段, 是一对多关系,需要在查询中增加一列,查询到A中的数据各关联了B的多少份数据.

思路,使用group by 和 count 查询出这些关联数据的份数. 然后作为一个中间表,再与A表进行 left join.

select a.*, v.sealSum from A a LEFT JOIN (
  select aa.id aaId,count(b.id) as sealSum from A aa
    LEFT JOIN B b
      on aa.id = b.business_id
        group by aa.id
  ) v on a.id = v.aaId

注意, 此处count()是有讲究的,因为主表是A, count(0)查的是以A为主表的条数. 我们此处需要关注的是A中关联了多少条B表中数据.故应该count(b.id)  B表中的某一列

猜你喜欢

转载自blog.csdn.net/qq_40085888/article/details/82839984