(1)同步存储:在区域表中有点位数的字段,当点位发生变化时,同步区域表中的点位数。
-
优点:由于是单表查询操作,查询列表效率最高。
-
缺点:需要在点位增删改时修改区域表中的数据,有额外的开销,数据也可能不一致。
(2)关联查询:编写关联查询语句,在mapper 层封装。
-
优点:实时查询,数据100%正确,不需要单独维护。
-
缺点:SQL语句较复杂,如果数据量大,性能比较低。
关联查询可以确保实时性和准确性
嵌套查询是将多表查询拆分成单个查询,在利用mybatis语法,将他们嵌套在一起,还能,提高查询的性能解决多表关联查询的难题,避免内存溢出的风险,同时保持代码的整洁和可维护性
通过定义的resultmap标签完成手动映射,包含association和collection元素,进行嵌套的关联
association:一对一或多对一映射结果只有一个对象时
collection:一对多的情况下映射多个结果的集合
他们两个可以同时实施
先执行关联查询,再进行嵌套查询,如下:
设计表
查询点位用关联,根据id查询两个信息用嵌套
他们都在一个查询条件中实现
-- 查询并显示点位表所有的字段信息,同时显示每个点位的设备数量 SELECT n.id, n.node_name, n.address, n.business_type, n.region_id, n.partner_id, n.create_time, n.update_time, n.create_by, n.update_by, n.remark, COUNT(v.id) AS vm_count FROM tb_node n LEFT JOIN tb_vending_machine v ON n.id = v.node_id GROUP BY n.id;
-- 根据区域id查询区域信息 select * from tb_region where id=1; -- 根据合作商id查询合作商信息 select * from tb_partner where id=1;
xml 中像这样写
通过resultmap指定,将两个单表查询的语句嵌套进去,实现三张表的查询,
其他的编写,如三层架构和前端index。vue和node。JS中,一摸一样
<resultMap id="NodeVoResult" type="NodeVo"> <result property="id" column="id" /> <result property="nodeName" column="node_name" /> <result property="address" column="address" /> <result property="businessType" column="business_type" /> <result property="regionId" column="region_id" /> <result property="partnerId" column="partner_id" /> <result property="createTime" column="create_time" /> <result property="updateTime" column="update_time" /> <result property="createBy" column="create_by" /> <result property="updateBy" column="update_by" /> <result property="remark" column="remark" /> <result property="vmCount" column="vm_count"/> <association property="region" javaType="Region" column="region_id" select="com.dkd.manage.mapper.RegionMapper.selectRegionById"></association> <association property="partner" javaType="Partner" column="partner_id" select="com.dkd.manage.mapper.PartnerMapper.selectPartnerById"></association> </resultMap>
<select id="selectNodeVoList" resultMap="NodeVoResult" > SELECT n.*, COUNT(vm.id) AS vm_count FROM tb_node n LEFT JOIN tb_vending_machine vm ON n.id = vm.node_id <where> <if test="nodeName != null and nodeName != ''"> and n.node_name like concat('%', #{nodeName}, '%')</if> <if test="regionId != null "> and n.region_id = #{regionId}</if> <if test="partnerId != null "> and n.partner_id = #{partnerId}</if> </where> GROUP BY n.id </select>