引入头文件 这些都是dao中的Mapper
<?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.maodou.scm.agent.dao.UnionQueryMapper">
这里a表和b表都有的字段是id a表中的id 是主键 b表中的agent_id是普通字段
我要从通过a和b id的关系 通过where中的判断语句找出来想要的数据
<select id >调用这个sql的名称
<resultType>这里放的是返回值得类型
select distinct
a.id as agentId
b.city_id as cityId
from agent a left join instance b
on a.id = b.agent_id
where
a.agent_code =1
and a.agent_name = "xxx"
and a.agent_status =0
and b.city_id =1
and b.item_id =22
实际的mapper中如何实现 上边是转成sql的样子
<mapper namespace="com.UnionQueryMapper">
<select id="selectAgentCityByCondition" resultType="com.QueryAgentCityDO">
SELECT DISTINCT
a.id as agentId,
b.city_id as cityId
FROM
agent a
LEFT JOIN agent_config_instance b ON a.id = b.agent_id
<where>
<if test="agentCode != null and agentCode != ''">
a.agent_code = #{agentCode,jdbcType=VARCHAR}
</if>
<if test="agentName != null and agentName != ''">
AND a.agent_name = #{agentName,jdbcType=VARCHAR}
</if>
<if test="agentStatus != null">
AND a.agent_status = #{agentStatus,jdbcType=INTEGER}
</if>
<if test="cityId != null">
AND b.city_id = #{cityId,jdbcType=INTEGER}
</if>
<if test="itemId != null">
AND b.item_id = #{itemId,jdbcType=INTEGER}
</if>
</where>
</select>
</mapper>
left join 就是把a表中的所有数据拉出来 把b表中 符合on条件的数据全都拿出来
没有的地方填null
a b表中的数据都要符合where的条件
如果为NOT NULL,那么mapper.xml中必须要验证<if test=" 字段名 !=null "></if>;
如果为非空字符串,则mapper.xml中必须要验证<if test=" 字段名!=‘ ’ "></if>。