MySQL查询 - 将3个表连接在一起,按列分组并计算其他2个表

时间:2011-10-03 23:50:27

标签: mysql join count

以下是我正在使用的3个表格的示例。


    Teams
    +----+------+
    | id | name |
    +----+------+
    |  1 | abc  |
    |  2 | def  |
    |  3 | ghi  |
    +----+------+


    Members
    +----+-----------+----------+---------+
    | id | firstname | lastname | team_id |
    +----+-----------+----------+---------+
    |  1 | joe       | smith    |       1 |
    |  2 | jared     | robinson |       1 |
    |  3 | sarah     | cole     |       3 |
    |  4 | jaci      | meyers   |       2 |
    +----+-----------+----------+---------+


    Goals
    +----+-----------+
    | id | member_id |
    +----+-----------+
    |  1 |         3 |
    |  2 |         2 |
    |  3 |         2 |
    |  4 |         3 |
    |  5 |         1 |
    +----+-----------+
    


我正在尝试查询输出类似的内容......


    Output
    +--------+----------------+-------------+
    | t.name | Count(members) | Count(goals)|
    +--------+----------------+-------------+
    | abc    |              2 |           3 |
    | def    |              1 |           2 |
    | ghi    |              1 |           0 |
    +--------+----------------+-------------+
    


这是我最接近的,但是当我在子查询中使用时,我得到“Subquery返回超过1行”。

select t.name, count(*), 
    (select count(*)
    from teams t 
    inner join members m on m.team_id = t.id
    group by t.id)
from teams t 
inner join members m on m.team_id = t.id 
inner join goals g on g.member_id = m.id
group by t.id

1 个答案:

答案 0 :(得分:2)

根据我的理解,这是我提出的查询:


    SELECT name, membersCount, IFNULL(totalCount, 0) goalsCount FROM
    (
      SELECT m.team_id, SUM(innerQuery.goalsCount) totalCount
      FROM (
        SELECT m.id memberId, COUNT(*) goalsCount
        FROM Members m
        JOIN Goals g
        ON m.id = g.member_id
        GROUP BY member_id
      ) innerQuery
      JOIN Members m
      ON innerQuery.memberId = m.id
      GROUP BY m.team_id
    ) inner_1
    RIGHT JOIN 
    (
      SELECT t.id, t.name, COUNT(*) membersCount
      FROM Teams t
      JOIN Members m
      ON t.id = m.team_id
      GROUP BY team_id
    ) inner_2
    ON inner_1.team_id = inner_2.id

查询细分:

#1。获取具有关联目标的成员ID(innerQuery)

 

SELECT m.id memberId, COUNT(*) goalsCount
    FROM Members m
    JOIN Goals g
    ON m.id = g.member_id
    GROUP BY member_id

#2。获取团队ID以及目标的总和(inner_1)

 

     SELECT m.team_id, SUM(innerQuery.goalsCount) totalCount
      FROM (
          .... Sub-query in step 1
      ) innerQuery
      JOIN Members m
      ON innerQuery.memberId = m.id
      GROUP BY m.team_id

#3。获得每个团队的成员总数(inner_2)

 

    SELECT t.id, t.name, COUNT(*) membersCount
      FROM Teams t
      JOIN Members m
      ON t.id = m.team_id
      GROUP BY team_id

#4。 RIGHT JOIN inner_1和inner_2(因为会有NULL)并使用IFNULL检查并替换0

 

    SELECT name, membersCount, IFNULL(totalCount, 0) goalsCount FROM
    (
     .... Sub-query in step 2
    ) inner_1
    RIGHT JOIN 
    (
      .... Sub-query in step 3
    ) inner_2
    ON inner_1.team_id = inner_2.id