2

我有一个表结构如下:

我还不能发布图片,所以一个作业有很多组和很多联系人,一个联系人有一个城市,一个城市有一个国家。

我想在每组的作业中计算国家/地区

并有以下查询

SELECT `parentCountry`.`id` as label ,count(`t`.`id`) as result, `parentGroup`.`description` as gr 
    FROM `assignment` `t` 
    LEFT OUTER JOIN `assignment_contact` `assignmentContacts`
        ON (`assignmentContacts`.`assignment`=`t`.`id`) 
    LEFT OUTER JOIN `contact` `relatedContact`
        ON (`assignmentContacts`.`contact`=`relatedContact`.`id`)
    LEFT OUTER JOIN `locator_city` `location`
        ON (`relatedContact`.`city`=`location`.`id`) 
    LEFT OUTER JOIN `locator_country` `parentCountry`
        ON (`location`.`country`=`parentCountry`.`id`) 
    LEFT OUTER JOIN `assignment_group` `activeGroup`
        ON (`activeGroup`.`assignment`=`t`.`id`) AND (activeGroup.active=1) 
    LEFT OUTER JOIN `group` `parentGroup`
        ON (`activeGroup`.`group`=`parentGroup`.`id`) 
GROUP BY gr,label
ORDER BY gr

运行这个查询让我得到类似的结果

Group1 ,Belgium, 6
Group1 ,Nederlands,3
Group2, Belgium, 1
Group2, UK,6 

我想得到结果

Group1 ,Belgium, 6
Group1 ,Nederlands,3
Group1 ,UK, 0
Group2, Belgium, 1
Group2, UK,6 
Group2, Nederlands,0

请帮忙,我花了好几个小时摆弄连接,得出结论我没有解决这个问题的“理论”方法。

禁止使用 UNIONS(即 FULL OUTER JOINS),但我真的认为不需要这样做。

编辑:我有一个可怕的解决方案,可以

请帮忙

4

1 回答 1

0

您需要确保带有国家/地区的表格排在第一位:

SELECT `parentCountry`.`id` as label ,count(`t`.`id`) as result, `parentGroup`.`description` as gr 
    FROM `locator_city` `location`
    LEFT OUTER JOIN `locator_country` `parentCountry`
        ON (`location`.`country`=`parentCountry`.`id`) 
    LEFT OUTER JOIN `contact` `relatedContact`
        ON (`relatedContact`.`city`=`location`.`id`) 
    LEFT OUTER JOIN `assignment_contact` `assignmentContacts`
        ON (`assignmentContacts`.`contact`=`relatedContact`.`id`)
    LEFT OUTER JOIN `assignment` `t` 
        ON (`assignmentContacts`.`assignment`=`t`.`id`) 
    LEFT OUTER JOIN `assignment_group` `activeGroup`
        ON (`activeGroup`.`assignment`=`t`.`id`) AND (activeGroup.active=1) 
    LEFT OUTER JOIN `group` `parentGroup` 
        ON (`activeGroup`.`group`=`parentGroup`.`id`) 
GROUP BY gr,label
ORDER BY gr
于 2013-09-18T06:51:00.923 回答