场景为多个数据表关联,驱动表与其他表存在一对多的关系,需要查询的数据包含两个表的字段及每条驱动表的数据对应关联表多少条数据的计数。ORM使用的是MyBatis。由于count函数会把数据聚合只剩一条数据,单纯使用count不能解决问题(今天才知道T T)。 最终采用了如下的配置文件。

<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="testmybatis.dao.mapper">
    <resultMap id="combinedResult" type="testmybatis.domain.Combine">
        <id property="id" column="ID" />
        <association property="a" javaType="testmybatis.domain.A">
          <id property="ID" column="ID"/>
          <result property="COLA" column="COLA"/>
        </association> 
        <association property="bs" javaType="testmybatis.domain.BS">     
            <result property="num" column="NUM"/>
            <collection property="bs" javaType="ArrayList" ofType="testmybatis.domain.B">
              <id property="ID" column="B_ID"/>
              <id property="COLA" column="B_COLA"/>
            </collection>
        </association>
    </resultMap>
    <select id="selectCombinedData" resultMap="combinedResult">
        select a.ID,a.COLA,b.ID as B_ID, b.COLA as B_COLA ,NUM from A,B,
        ( select A.ID,count(*) as NUM from A,B where A.ID = B.ID group by B.ID ) as C
        where A.ID = B.ID and B.ID = C.ID;
    </select>
</mapper>

基本原理就是,将驱动表ID和计数作为C表与原来的两张表再次联表。由于实际业务场景,关联的表不止一张,这样的操作与在内存中对数据进行遍历再计数的性能还不知道哪个会好一点,需要进一步做实验进行验证。