mysql left join query results are not accurate

Existing four tables

表(1)res_resource_catalog

表(2)res_catalog_classify

表(3)res_resource_classify

表(4)res_resource_mount

Wherein the intermediate table 3 is a table of Table 1 and Table 2, a primary key table is a foreign key in table 4

The amount of data in tables 2 now a type of the current user created tables 1, Table 1 and Table 4, the amount of data related to

sql beginning as follows:

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

Query results are not accurate, when createUser did not create the data in Table 1, the query result is null, the actual data in Table 2 should be there, but the results resourceCatalogCount is 0, sql Corrected as follows:

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

 

Guess you like

Origin www.cnblogs.com/cailijuan/p/11652356.html