mysql左连接查询结果不准确
Posted 無玑小姐
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mysql左连接查询结果不准确相关的知识,希望对你有一定的参考价值。
现有四张表
表(1)res_resource_catalog
表(2)res_catalog_classify
表(3)res_resource_classify
表(4)res_resource_mount
其中,表3是表1和表2的中间表,表1的主键是表4的外键
现在要统计表2中某一类型的表1的当前用户创建的数据量,以及表1相关的表4的数据量
一开始的sql如下:
SELECT rcc.id, rcc.catalog_name, COUNT(DISTINCT rrc.id) AS resourceCatalogCount,COUNT(DISTINCT rrm.id) AS resourceCount FROM (SELECT * FROM res_catalog_classify WHERE catalog_type = #{catalogType} AND parent_id != \'0\' AND is_publish = 1) rcc LEFT JOIN res_resource_classify rrc ON rcc.id = rrc.classify_id LEFT JOIN res_resource_catalog rrc1 ON rrc.resource_id = rrc1.id LEFT JOIN res_resource_mount rrm ON rrc.resource_id = rrm.resource_id <where> <if test="createUser != null and createUser != \'\'"> AND rrc1.create_user = #{createUser} </if> AND rrc1.is_publish = 1 </where> GROUP BY rcc.id
结果查询不准确,当createUser没有在表1中创建数据时,查询结果为null,实际应该是表2数据有,但是结果中的resourceCatalogCount为0,经改正后的sql如下:
SELECT rcc.id, rcc.catalog_name, COUNT(DISTINCT rrc1.id) AS resourceCatalogCount,COUNT(DISTINCT rrm.id) AS resourceCount FROM (SELECT * FROM res_catalog_classify WHERE catalog_type = #{catalogType} AND parent_id != \'0\' AND is_publish = 1) rcc LEFT JOIN res_resource_classify rrc ON rcc.id = rrc.classify_id LEFT JOIN ( SELECT * FROM res_resource_catalog <where> <if test="createUser != null and createUser != \'\'"> AND rrc1.create_user = #{createUser} </if> AND rrc1.is_publish = 1 </where> ) rrc1 ON rrc.resource_id = rrc1.id LEFT JOIN res_resource_mount rrm ON rrc.resource_id = rrm.resource_id GROUP BY rcc.id
以上是关于mysql左连接查询结果不准确的主要内容,如果未能解决你的问题,请参考以下文章