标签:user null 相关 name join use group by sele distinct
现有四张表
表(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
标签:user null 相关 name join use group by sele distinct
原文地址:https://www.cnblogs.com/cailijuan/p/11652356.html