-4

我有以下表格:

CREATE TABLE 成员 (
  member_id int(1) 无符号 NOT NULL AUTO_INCREMENT,
  登录 tinyint(1) 非空,
  主键(member_id),
  唯一键 member_id (member_id)
) 引擎=InnoDB 默认字符集=utf8;

插入成员(member_id,logged_in)值
  (1, 0),
  (2, 1),
  (3, 1),
  (4, 1),
  (5, 0);

+------------------------+
| 会员 |
+-----------+------------+
| 会员编号 | 登录 |
+-----------+------------+
| 1 | 0 |   
| 2 | 1 |
| 3 | 1 |
| 4 | 1 |
| 5 | 0 |
+-----------+------------+
创建表 team_members (
  team_id int(1) 无符号非空,
  member_id int(1) 无符号非空,
  主键 (team_id,member_id)
) 引擎=InnoDB 默认字符集=utf8;

插入到 team_members (team_id, member_id) 值
  (1, 1),
  (1, 2),
  (2, 3),
  (2, 4),
  (3, 5);

+----------+
| 团队成员 |
+---------+-----------+
| team_id | 会员编号 |
+---------+-----------+
| 1 | 1 |
| 1 | 2 |
| 2 | 3 |
| 2 | 4 |
| 3 | 5 |
+---------+-----------+

这是我需要实现的输出:

+---------+----------+
| team_id | 登录用户数 |
+---------+----------+
| 1 | 1 |
| 2 | 2 |
| 3 | 0 |
+---------+----------+

我正在尝试以下 sql 查询,但它没有返回预期的输出:

选择
  tm.team_id,
  (SELECT COUNT(m.logged_in) FROM members m WHERE m.logged_in = 1) AS logged_in_users_count
从
  会员米
  INNER JOIN team_members tm ON (m.member_id = tm.member_id)
通过...分组
  tm.team_id
4

1 回答 1

2
选择
 team_members.team_id,
 COUNT(members.logged_in)
从
 team_members LEFT JOIN members
 ON (team_members.member_id = members.member_id AND members.logged_in = 1)
GROUP BY
  team_members.team_id;
于 2012-04-27T14:33:36.483 回答