Mysql很多加入

时间:2013-09-18 06:29:44

标签: mysql sql

我有一个表结构如下:

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

我想按国家/地区分配任务分配中的国家/地区

并有以下查询

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),但我真的认为不应该这样做。

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

请帮忙

1 个答案:

答案 0 :(得分: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