MyBatis LEFT JOIN 与筛选条件:为何数据仍能返回?
MyBatis LEFT JOIN 与筛选条件:为何数据仍能返回?
在使用 MyBatis 进行数据库查询时,我们经常会用到 LEFT JOIN 来连接多个表。当在 LEFT JOIN 的基础上添加筛选条件时,如果条件不成立,我们会发现 MyBatis 仍然可以返回数据,这引发了一些疑惑。
问题示例:
假设我们有一个查询语句如下:
<select id="queryPages" parameterType="string" resultType="org.jeecg.modules.pureSilverOrderService.entity.PureSilverOrder">
SELECT
pso.id,pso.create_time,pso.material_document,
pso.material_document_item,pso.posting_date,pso.material,
p.ProductDescription AS materialName,pso.quantity,pso.unit,pso.batch,
pso.goods_movement_type,pso.plant,pso.storage_location,
pso.manufacturing_order,pso.is_system_post,pso.is_hand_post
FROM
pure_silver_order pso
LEFT JOIN
ods_product p ON p.Product = pso.material
WHERE 1=1
<if test="pureSilverOrder.isPost != null and pureSilverOrder.isPost == '1'">
AND (pso.is_system_post = 'Y' OR pso.is_hand_post = 'Y')
</if>
<if test="pureSilverOrder.isPost != null and pureSilverOrder.isPost == '2'">
AND pso.is_system_post = 'N' AND pso.is_hand_post = 'N'
</if>
ORDER BY create_time ASC
</select>
当数据库中只有一条数据,并且 is_system_post,is_hand_post 都为 N;当筛选条件 isPost 的值为 1 的时候,为什么 MyBatis 还可以返回这一条数据内容?
解析:
根据给出的查询语句和条件,当筛选条件 isPost 的值为 1 时,<if> 标签中的条件 (pso.is_system_post = 'Y' OR pso.is_hand_post = 'Y') 不成立,因为 is_system_post 和 is_hand_post 都为 N。
但是由于使用了 LEFT JOIN,即使条件不成立,仍然会返回 pure_silver_order 表中的一条数据,即使 ods_product 表中没有匹配的记录。这就是为什么 MyBatis 可以返回这一条数据的原因。
总结:
LEFT JOIN 的特点是:
- 如果
ods_product表中存在与pure_silver_order表中数据匹配的记录,则返回匹配的记录。 - 如果
ods_product表中不存在与pure_silver_order表中数据匹配的记录,则返回pure_silver_order表中数据,并使用NULL值填充ods_product表中的字段。
因此,即使筛选条件不成立,仍然可以返回 pure_silver_order 表中数据,因为 LEFT JOIN 会返回所有 pure_silver_order 表中的数据,并根据匹配情况填充 ods_product 表中的字段。
原文地址: https://www.cveoy.top/t/topic/dnyJ 著作权归作者所有。请勿转载和采集!