我的mysql架构如下所示:
+---------+---------+----------+ +---------+-----------+
| user_id | club_id | username | | club_id | club_name |
+---------+---------+----------+ +---------+-----------+
| 1 | 1 | bob | | 1 | bobcats |
| 2 | 1 | tom | | 2 | carguys |
| 3 | 1 | sam | +---------+-----------+
| 4 | 2 | mat |
+---------+---------+----------+
我想要一个返回的选择查询:
+---------+-----------+-------------+
| club_id | club_name | num_members |
+---------+-----------+-------------+
| 1 | bobcats | 3 |
| 2 | carguys | 1 |
+---------+-----------+-------------+
我试过了:
SELECT clubs.club_id
, clubs.club_name
, COUNT(DISTINCT users.club_id) AS num_members
FROM users
JOIN clubs
on users.club_id = clubs.club_id
ORDER
BY clubs.club_name
当我尝试时(仅第一排而不是所有球杆)我得到了什么:
+---------+-----------+-------------+
| club_id | club_name | num_members |
+---------+-----------+-------------+
| 1 | bobcats | 3 |
+---------+-----------+-------------+