MyBatis - 如何从同一 table 连接多个列

MyBatis - How to join multiple columns from same table

我正在尝试学习如何将一个 table 的多个列连接到另一个 table 的一个列,对于给定的 ID。

这是我的团队 table:

create table teams ( 
  id varchar(10),
  name varchar(30),
  primary key (id)
);

这是我的团队赛table:

create table teammatch (
  id integer,
  firstTeamId varchar,
  secondTeamId varchar,
  matchId integer,
  primary key(id),
  foreign key (firstTeamId) references teams (id),
  foreign key (secondTeamId) references teams (id)
);

我的sql:

select teammatch.*, t1.*, t2.*
    from teammatch
    inner join teams t1 on teammatch.firstTeamId = t1.id
    inner join teams t2 on teammatch.secondTeamId = t2.id
    where teammatch.id = #{id}

数据:

ID      FIRSTTEAMID     SECONDTEAMID 
1       POR             DEN 
2       TOR             PHI 

This query returns POR team for both t1 and t2 但我需要它 return t1 的 POR 和 t2 的 DEN

编辑: 当我在 H2 数据库中编写 sql 查询时,这工作正常,但是当我在 xml 映射器文件中用 mybatis 编写它时,它 return 两个字段的值相同。

这是我的 ResultMap

<resultMap id="TeamMatchMap" type="TeamMatch">
    <id column="id" property="id" />

    <association property="firstTeamId" column="firstTeamId" javaType="Team">
      <id column="id" property="id" />
      <result column="name" property="name" />
    </association>

    <association property="secondTeamId" column="secondTeamId" javaType="Team">
      <id column="id" property="id" />
      <result column="name" property="name" />
    </association>
  </resultMap>

请尝试将您的映射器更改为这样的东西

<?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>
    <select id="getTeammatches"
            resultMap="teamMatchMap">
        select
            teammatch.id as matchid       ,
            t1.id        as firstteam_id  ,
            t1.name      as firstteam_name,
            t2.id        as secondteam_id ,
            t2.name      as secondteam_name
          from teammatch
            inner join teams t1 on teammatch.firstTeamId = t1.id
            inner join teams t2 on teammatch.secondTeamId = t2.id
          where teammatch.id = #{id}
    </select>
    <resultMap type="TeamMatch" id="teamMatchMap">
        <result property="id" column="MATCHID"/>
        <association property="team1" columnPrefix="FIRSTTEAM_" resultMap="teamMap"/>
        <association property="team2" columnPrefix="SECONDTEAM_" resultMap="teamMap"/>
    </resultMap>
    <resultMap type="Team" id="teamMap">
        <result property="id" column="ID"/>
        <result property="name" column="NAME"/>
    </resultMap>
</mapper>

通过为 Team 声明单独的 resultMap 或引用现有的 resultMap,您不需要在 association 标签的 body-tag 中映射列两次

你为 association 使用了 column-Attribute - 据我所知,它仅在你希望 myBatis 执行另一个 select-tag

时使用

编辑

我在阅读您的编辑和评论之前写了映射器

如果您的 Team-class 提供了一个带有 id 和 name 的构造函数,您的 teamMap 也可以像这样

    <resultMap type="Team" id="teamMap">
        <constructor>
            <idArg column="ID"/>
            <arg column="NAME"/>
        </constructor>
    </resultMap>