简体   繁体   中英

How to join row count of each group from right side table

I have two tables i) team ii) team_member. The team_member table holds all member under each team.

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 :

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. 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 :

+------------------+
|  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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM