SQL语句两种方式实现关联查询

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
                PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
                "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jt.mapper.RightsMapper">

<!--利用左查询,查询出同表父子关系表-->
<select id="getRights" resultMap="rightsRM">
    SELECT p.id,p.name,p.parent_id,p.path,p.level,p.created,p.updated,
   c.id AS c_id,c.name AS c_name,c.parent_id AS c_parent_id,c.path AS c_path,
   c.level AS c_level,c.created AS c_created,c.updated AS c_updated
    FROM
(SELECT * FROM rights WHERE parent_id=0) AS p
   LEFT JOIN
      rights AS c
    ON p.id =c.parent_id
</select>
   <!--
     1.id 标签代表逐渐(每张表都会有一个主键)
           column: 返回集的字段名
           property: 封装的对象对应的属性
     2.result 标签代表主键以外的字段
           column: 返回集的字段名
           property: 封装的对象对应的属性
            -->
   <resultMap id="rightsRM" type="Rights" autoMapping="true">
      <id column="id" property="id"/>
         <!--oftype pojo里面对应对象的集合中的类型-->
      <collection property="children" ofType="Rights">
            <!--下面的数据库字段名字和对象里的属性不符合,需要一个一个写出来-->
         <id column="c_id" property="id"/>
         <result column="c_name" property="name" />
         <result column="c_parent" property="parentId" />
         <result column="c_path" property="path" />
         <result column="c_level" property="level" />
         <result column="c_created" property="created" />
         <result column="c_updated" property="updated" />
      </collection>

   </resultMap>


   <!--利用分表关联查询-->
   <select id="getRights2" resultMap="RightsRM">
      select *from rights where  parent_id = 0
   </select>

   <resultMap id="RightsRM" type="Rights" autoMapping="true">
      <id property="id" column="id"></id>
      <collection property="children" ofType="Rights" select="childrenIdByParent"   column="id"/>
   </resultMap>

   <select id="childrenIdByParent"  resultType="Rights" >
      select * from rights where parent_id = #{id}
   </select>

</mapper>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值