码迷,mamicode.com
首页 > 数据库 > 详细

mysql左连接查询结果不准确

时间:2019-10-11 10:28:27      阅读:122      评论:0      收藏:0      [点我收藏+]

标签: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

技术图片

 

mysql左连接查询结果不准确

标签:user   null   相关   name   join   use   group by   sele   distinct   

原文地址:https://www.cnblogs.com/cailijuan/p/11652356.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!