MyBatis如何实现多表联查
时间: 2024-01-23 09:03:15 浏览: 25
MyBatis可以通过使用嵌套查询、关联查询和动态SQL等方式实现多表联查。
1. 嵌套查询
嵌套查询是指在一个SQL语句中嵌套另一个SQL语句进行查询。例如:
```
<select id="getUserOrders" resultType="User">
select * from user where id=#{userId}
<select id="getOrdersByUserId" resultType="Order">
select * from order where user_id=#{userId}
</select>
</select>
```
这个例子中,我们先查询出指定用户的信息,然后通过嵌套查询获取该用户的所有订单信息。
2. 关联查询
关联查询是指通过连接两个或多个表,根据表之间的关系进行查询。例如:
```
<select id="getUserOrders" resultMap="userOrderMap">
select u.*, o.*
from user u
left join order o on u.id=o.user_id
where u.id=#{userId}
</select>
<resultMap id="userOrderMap" type="User">
<id property="id" column="id"/>
<result property="name" column="name"/>
<collection property="orders" ofType="Order">
<id property="id" column="order_id"/>
<result property="name" column="order_name"/>
</collection>
</resultMap>
```
这个例子中,我们通过左连接将用户表和订单表关联起来,然后通过resultMap将查询结果映射到User对象中,并且将该用户的所有订单映射到orders集合中。
3. 动态SQL
动态SQL是指根据不同的条件动态生成SQL语句。例如:
```
<select id="getUserOrders" resultMap="userOrderMap">
select u.*, o.*
from user u
left join order o on u.id=o.user_id
<where>
<if test="userId != null">
and u.id=#{userId}
</if>
<if test="orderStatus != null">
and o.status=#{orderStatus}
</if>
</where>
</select>
```
这个例子中,我们通过if标签判断userId和orderStatus是否为空,如果不为空则加入对应的查询条件,从而动态生成SQL语句。这样就可以根据不同的条件进行多表联查。