子查询中的COUNT

时间:2013-04-13 00:49:02

标签: mysql sql

我有一个html表格,我想要显示cht_namecount_hohcount_members。我可以在count_hoh中获得计数结果,因为cht_id上的household_tbl字段与tbl_cht_members上的主表格相同。我无法获取count_members的计数,该表tbl_household_membershousehold_tbl上具有相同字段,但没有字段cht_id我可以直接在count_hoh上得到相同的计数。我只是通过household_connector_id链接它们。

SELECT cht_id as cht, name, 
       (SELECT household_connector_id as hoh,
               COUNT(*) 
          FROM household_tbl 
         WHERE cht_id = cht) as count_hoh,
       (SELECT COUNT(*) 
          FROM tbl_household_members 
         WHERE household_connector_id = hoh) as count_members
  FROM tbl_cht_members 
GROUP BY cht_id

2 个答案:

答案 0 :(得分:0)

尝试这种疯狂猜测;)

SELECT 
    tbl_cht_members.cht_id as cht, tbl_cht_members.name,
    COUNT(household_tbl.cht_id) AS count_hoh,
    COUNT(tbl_household_members.household_connector_id) AS count_members
FROM
    tbl_cht_members LEFT JOIN household_tbl 
        ON tbl_cht_members.cht_id = household_tbl.cht_id
    LEFT JOIN tbl_household_members
        ON household_tbl.household_connector_id = tbl_household_members.household_connector_id

您可能会修复一些字段/表名称和/或使用DISTINCT但该概念将适用于IMO

答案 1 :(得分:0)

由于家庭已经有了正确的关系,你可以加入它并按关系(cht_id)进行分组并获得你的计数。

但由于成员表具有二级关系并且您想要另一个求和,您必须“预先聚合”它并通过您的相关表格(household_tbl)公开关系。

     SELECT cht_id as cht, 
            name, 
            count(*) as households_cnt,
            members.cnt as member_cnt
       FROM tbl_cht_members cht
  LEFT JOIN household_tbl households  
         ON households.cht_id = cht.cht_id
  LEFT JOIN (SELECT ht.cht_id, count(*) as cnt
               FROM tbl_household_members thm 
               JOIN household_tbl ht 
                 ON thm.household_connector_id = ht.household_connector_id
              GROUP BY thm.cht_id) members
         ON members.cht_id = cht.cht_id
   GROUP BY cht.cht_id, name, members.cnt

另请注意:组织表格命名确实很有帮助。你有“tbl”作为前置和后置修复 - 非常令人困惑。事实上,我可能会把它完全抛弃。