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