0

我有一个 html 表格,我想在其中显示cht_name,count_hohcount_members. 我可以得到计数的结果,count_hoh因为我有相同的字段cht_idonhousehold_tbl和主表 on tbl_cht_members。我在获取具有相同字段但没有字段count_members的表的计数时遇到了麻烦,我可以在其中直接获取相同的计数。我只是通过.tbl_household_membershousehold_tblcht_idcount_hohhousehold_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
4

2 回答 2

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

于 2013-04-13T01:26:25.117 回答
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”作为前修复和后修复 - 非常令人困惑。事实上,我可能会把它完全排除在外。

于 2013-04-13T02:58:50.073 回答