如何在多连接查询中正确连接和计数

时间:2016-08-10 16:21:24

标签: sql join count group-by multiple-tables

我的主要表格属性包括:

id (index primary id)
community_code
section_code
lot (index unique)

我有两个查找表:

社区表:

id (index primary id)
code (index unique - relates to properties.community_code)
name

章节表:

id (index primary id)
community_id (index - relates to communities.id)
code (index - relates to properties.section_code)
name (index)

我试图按社区部分汇总抽签计数,并返回社区ID,社区名称和部门名称,其结果如下:

|communityId|communityCode|communityName|sectionCode|sectionName|numLots|
|1          |CAG          |Community CAG|1          |Section 1  |156    |
|1          |CAG          |Community CAG|2          |Section 2  |44     |
|1          |CAG          |Community CAG|3          |Section 3  |100    |
|2          |CKS          |Community CKS|Q          |Section Q  |102    |
|2          |CKS          |Community CKS|X          |Section X  |78     |
|2          |CKS          |Community CKS|Z          |Section Z  |10     |

这是我建立的查询:

SELECT 
    c.id as 'communityId',
    p.community_code as 'communityCode', 
    c.name as 'communityName', 
    p.section_code as 'sectionCode', 
    s.name as 'sectionName', 
    COUNT(p.section_code) as 'numLots'
FROM properties_master p
JOIN communities c ON p.community_code = c.code
JOIN sections s ON p.section_code = s.code AND c.id = s.community_id
GROUP BY p.section_code
ORDER BY c.name ASC, s.name ASC

看起来它运行正常,直到我手动检查numLots的总数并且它们不正确。有些很高,有些很低。有趣的是,如果你对这个查询产生的所有数据求和,则总批次实际上与属性表中的总批次相同。

我无法弄清楚这个查询有什么问题。

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

发现了我自己的错误。我需要对community_code和section_code进行分组。

这是正确的查询:

        SELECT 
            c.id as 'communityId',
            p.community_code as 'communityCode', 
            c.name as 'communityName',
            s.id as 'sectionId',
            p.section_code as 'sectionCode',
            s.name as 'sectionName',
            COUNT(p.section_code) as 'numLots'
        FROM properties_master p
        LEFT JOIN communities c ON p.community_code = c.code
        LEFT JOIN sections s ON c.id = s.community_id AND p.section_code = s.code
        GROUP BY p.community_code, p.section_code
        ORDER BY p.community_code ASC, p.section_code ASC