Mybatis plus 多表联查字段名重复报错 Column ‘id‘ in where clause is ambiguous


 

一、报错信息

Caused by: Column 'xxxx' in where clause is ambiguous

二、报错原因

表 person 和 表 class 都有字段 id 和 name ,所以要给它们增加别名来进行区分。

PersonVOMapper.java
public interface PersonVOMapper extends BaseMapper<PersonVO> { List<PersonVO> getPersonVOList(@Param(Constants.WRAPPER) Wrapper<PersonVO> queryWrapper); } 

 

 

PersonVOMapper.xml
<?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.sionas.mapper.PersonVOMapper"> <select id="getPersonVOList" resultType="com.sionas.domain.PersonVO"> SELECT p.id AS personId, p.name AS personName, p.sex, p.age, c.id AS classId, c.name AS className FROM person p LEFT JOIN class c ON c.id = p.class_id; ${ew.customSqlSegment} </select> </mapper> 

 

 

${ew.customSqlSegment} 是Mybatis Plus的动态条件构造器的最终条件SQL

PersonServiceImpl.java

LambdaQueryWrapper<PersonVO> wrapper = new LambdaQueryWrapper<>(); wrapper.like(PersonVO::getPersonName, keyword) .or().like(PersonVO::getClassName, keyword); List<PersonVO> list = personVOMapper.getPersonVOList(wrapper); 

 

 

此时会报错 Column ‘name’ in where clause is ambiguous,意思是 where子句中的列“name”是不明确的

原因: 多表查询后字段 name 是重复的,查询结果集中含有两个 name 不知道是哪一个才是要查询的。条件语句是针对查询结果集的,所以此时的 字段重命名无效


三、解决方法

方法一:

使用明确的字段名称 表名.字段名


LambdaQueryWrapper<PersonVO> wrapper = new LambdaQueryWrapper<>(); wrapper.like("p.name", keyword) .or().like("c.name", keyword); List<PersonVO> list = personVOMapper.getPersonVOList(wrapper); 

 

 

方法二:

把查询结果作为子查询,然后再增加条件语句

        SELECT * FROM ( SELECT p.id AS personId, p.name AS personName, p.sex, p.age, c.id AS classId, c.name AS className FROM person p LEFT JOIN class c ON c.id = p.class_id ) AS result ${ew.customSqlSegment} 

 

 

可以直接使用如下方式进行查询而不需要补全表名:


LambdaQueryWrapper<PersonVO> wrapper = new LambdaQueryWrapper<>(); wrapper.like(PersonVO::getPersonName, keyword) .or().like(PersonVO::getClassName, keyword); List<PersonVO> list = personVOMapper.getPersonVOList(wrapper); 

 

 

 
 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM