连接多个表时如何创建正确的mysql查询

时间:2019-07-09 17:25:40

标签: mysql

我正在寻找有关创建查询的帮助,该查询将用于显示一些统计信息。我对mysql不太熟悉,因此想出一些办法很棘手。

我有3个表,其中包含有关组织的信息。这些是表格:

   Organizations                         Teams
+-----------------+          +--------------------------+
| ORGID | ORGNAME |          | TEAMID| ORGID | TEAM NAME|
+-----------------+          +--------------------------+
|   1   |  ORG A  |          |   1   |   1   |  TEAM A  |
+-----------------+          +--------------------------+
                             |   2   |   1   |  TEAM B  |
                             +--------------------------+
   Team Members
+-----------------------------------------------------------------------+
| MEMBERID | TEAMID | MEMBER NAME | FIRST ACTIVE | LAST ACTIVE | ACTIVE |
+-----------------------------------------------------------------------+
|    1     |    1   |     BOB     |  2019-05-01  |  2019-06-05 |   N    |
+-----------------------------------------------------------------------+
|    2     |    1   |    JANE     |  2019-06-01  |  2019-07-09 |   Y    |   
+-----------------------------------------------------------------------+
|    3     |    2   |     PAT     |  2019-07-01  |  2019-07-09 |   Y    |   
+-----------------------------------------------------------------------+

我要进行的查询将显示团队,他们有多少个成员以及我的成员如何不活跃。因此,我的期望将类似于:

+----------------------------------------+
|  TEAM  | MEMBER COUNT | INACTIVE COUNT |
+----------------------------------------+
| TEAM A |      2       |        1       |
+----------------------------------------+
| TEAM B |      1       |        0       |
+----------------------------------------+

获取每一列的结果都是微不足道的,但是将它们组合在一起是我遇到问题的地方。

我想到的第一个查询是:

SELECT teams.teamname AS teamname, COUNT(DISTINCT teammembers.memberid) AS members, COUNT(teammembers.active) AS active FROM teams
LEFT JOIN teammembers ON teams.teamid = teammembers.teamid
LEFT JOIN organizations ON teams.orgid = organizations.orgid
WHERE organizations.orgname = 'ORG A'
AND teammembers.active = 'N'
GROUP BY teams.teamname;

此查询返回的结果不准确,我只是在计算未激活的=“ N”的结果。

我不确定是否没有正确连接这些表,还是应该使用子查询。希望有人可以帮助指导我取得正确的结果。我可以提供更多信息。

1 个答案:

答案 0 :(得分:1)

您必须从AND teammembers.active = 'N'子句中删除条件WHERE,因为这不会计算所有成员仅购买非活动成员:

SELECT 
  t.teamname AS teamname, 
  COUNT(DISTINCT m.memberid) AS members_count, 
  SUM(m.active = 'N') AS inactive_count 
FROM teams t
LEFT JOIN teammembers m ON t.teamid = m.teamid
LEFT JOIN organizations o ON t.orgid = o.orgid
WHERE o.orgname = 'ORG A'
GROUP BY t.teamname;

使用SUM(m.active = 'N'),您可以计算不活动的成员。
另外,我认为没有必要对DISTINCT使用COUNT(DISTINCT m.memberid)(尽管我保留了它)。同一团队有两排的团队成员是否有案子?