当前位置:   article > 正文

Mybatis多表查询,报错:Column ‘id‘ in field list is ambiguous_column 'id' in field list is ambiguous

column 'id' in field list is ambiguous

Mybatis多表查询,报错:Column 'id' in field list is ambiguous

Mybatis错误示例:

  1. <resultMap id="JoinResultMap" type="com.WorkDto">
  2. <id column="id" jdbcType="BIGINT" property="id"/>
  3. <result column="work_city_code" jdbcType="VARCHAR" property="workCityCode"/>
  4. <collection property="guardInfos" ofType="com.GuardInfo">
  5. <id column="id" jdbcType="BIGINT" property="id" />
  6. <result column="work_id" jdbcType="BIGINT" property="workId" />
  7. <result column="guarder_code" jdbcType="VARCHAR" property="guarderCode" />
  8. </collection>
  9. </resultMap>
  10. <select id="selectById" parameterType="java.lang.Long" resultMap="JoinResultMap">
  11. select t1.id, work_city_code,
  12. t2.id , t2.work_id, t2.guarder_code
  13. from tt_work t1
  14. left join tt_work_info t2
  15. on t1.id=t2.work_id
  16. where id = #{id,jdbcType=BIGINT}
  17. </select>

以上会报错:Column 'id' in field list is ambiguous

错误原因:

Mybatis 多表查询时,多个表有相同名字的字段,比如 id,名字重复,没有指定对应的表名。
有两个地方需要注意:(1)将其中一个重复字段的 Mybatis的 column 修改为其他的名字。(2)字段加上对应的表名。

修改如下:

以下将
(1)其中一个id对应的 column 修改为其他的不重复的名称 guarder_info_id
(2)给查询结果和查询条件中的 id 加上表名 t1.id

  1. <resultMap id="JoinResultMap" type="com.WorkDto">
  2. <id column="id" jdbcType="BIGINT" property="id"/>
  3. <result column="work_city_code" jdbcType="VARCHAR" property="workCityCode"/>
  4. <collection property="guardInfos" ofType="com.GuardInfo">
  5. <id column="guarder_info_id" jdbcType="BIGINT" property="id" />
  6. <result column="work_id" jdbcType="BIGINT" property="workId" />
  7. <result column="guarder_code" jdbcType="VARCHAR" property="guarderCode" />
  8. </collection>
  9. </resultMap>
  10. <select id="selectById" parameterType="java.lang.Long" resultMap="JoinResultMap">
  11. select t1.id, work_city_code,
  12. t2.id as guarder_info_id, t2.work_id, t2.guarder_code
  13. from tt_work t1
  14. left join tt_work_info t2
  15. on t1.id=t2.work_id
  16. where t1.id = #{id,jdbcType=BIGINT}
  17. </select>
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/625115
推荐阅读
相关标签