簡體   English   中英

如何從右側表中加入每個組的行數

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

我有兩個表 i)團隊 ii)team_member。 team_member 表包含每個團隊下的所有成員。

團隊表看起來像這樣:

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

我期待的結果是這樣的:

+------------------+
|  expected result |
|------------------|
|  id |    count   |
|------------------|
|  1  |      2     |
|------------------|
|  2  |      1     |
|------------------|
|  3  |      0     |
|------------------|
|  5  |      0     |
+------------------+

它基本上是團隊每個組下所有活躍成員的數量。

我的 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

現在出現的問題是 SQL 查詢部分工作。如果每個團隊至少有一個成員,那么查詢工作正常。 如果它找到一個沒有成員的組,那么它會將其添加到結果中,但在那之后停止。

所以如果 team_member 表為空,我得到的結果是這樣的:

+------------------+
|  expected result |
|------------------|
|  id |    count   |
|------------------|
|  1  |      0     |
+------------------+

任何人都可以請停止查詢錯誤的地方以及正確的查詢應該是什么。

謝謝你。

team.id而不是team_member.team_id數據進行team.id ,因為team_member表不包含所有團隊 ID。

嘗試這個:

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 小提琴示例: http ://sqlfiddle.com/#!9/65a397/2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM