7

Mybatis plus 多表联查Column ‘id‘ in where clause is ambiguous 转载

 2 years ago
source link: https://segmentfault.com/a/1190000040773588
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Mybatis plus 多表联查Column ‘id‘ in where clause is ambiguous 转载

发布于 今天 04:32

转载自 https://blog.csdn.net/qq_3383...

一、报错信息
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);

————————————————
版权声明:本文为CSDN博主「Siona_xin」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_3383...


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK