[英]How to join row count of each group from right side table
I have two tables i) team ii) team_member.我有两个表 i)团队 ii)team_member。 The team_member table holds all member under each team.
team_member 表包含每个团队下的所有成员。
Team Table look like this :团队表看起来像这样:
+-----------------------+ | team | |-----------------------| | id | name | status | |-----------------------| | 1 | Team 1 | Active | |-----------------------| | 2 | Team 2 | Active | |-----------------------| | 3 | Team 3 | Active | |-----------------------| | 4 | Team 4 |Inactive| |-----------------------| | 5 | Team 5 | Active | +-----------------------+
Team Member Table look like this :团队成员表如下所示:
+--------------------------------------+ | team_member | |--------------------------------------| |tm_id| team_id | user_id | status | |--------------------------------------| | 1 | 1 | 2 | Inactive | |--------------------------------------| | 2 | 1 | 2 | Active | |--------------------------------------| | 3 | 1 | 3 | Active | |--------------------------------------| | 4 | 2 | 4 | Active | |--------------------------------------| | 5 | 2 | 5 | Inactive | +--------------------------------------+
What result I'm expecting is this :我期待的结果是这样的:
+------------------+ | expected result | |------------------| | id | count | |------------------| | 1 | 2 | |------------------| | 2 | 1 | |------------------| | 3 | 0 | |------------------| | 5 | 0 | +------------------+
It is basically number of all active member under each group of the team.它基本上是团队每个组下所有活跃成员的数量。
My SQL query is this :我的 SQL 查询是这样的:
SELECT team.id, COUNT( team_member.tm_id )
FROM `team`
LEFT JOIN team_member ON team_member.team_id = team.id
AND team_member.status = 'Active'
GROUP BY team_member.team_id
Now the issue arising is the SQL query is working partially.If each team has, at least, one member then the query works fine.现在出现的问题是 SQL 查询部分工作。如果每个团队至少有一个成员,那么查询工作正常。 if it finds one group without member then it is adding that in the result but stops after that.
如果它找到一个没有成员的组,那么它会将其添加到结果中,但在那之后停止。
so the result I'm getting is this if team_member table is blank :所以如果 team_member 表为空,我得到的结果是这样的:
+------------------+ | expected result | |------------------| | id | count | |------------------| | 1 | 0 | +------------------+
Can anyone please stop where the query is wrong and what should be the correct query.任何人都可以请停止查询错误的地方以及正确的查询应该是什么。
Thank You.谢谢你。
Group data by team.id
instead of team_member.team_id
because team_member
table does not contains all the Team ID's.按
team.id
而不是team_member.team_id
数据进行team.id
,因为team_member
表不包含所有团队 ID。
Try this:尝试这个:
SELECT team.id, COUNT( team_member.tm_id )
FROM `team`
LEFT JOIN team_member ON team_member.team_id = team.id
AND team_member.status = 'Active'
GROUP BY team.id;
SQL Fiddle Example : http://sqlfiddle.com/#!9/65a397/2 SQL 小提琴示例: http ://sqlfiddle.com/#!9/65a397/2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.