有下列users和clans表:
mid | clan_id |
---|---|
1 | 1 |
2 | 2 |
3 | 2 |
4 | 3 |
clan_id | clan_name | membership |
---|---|---|
1 | A | null |
2 | B | null |
3 | C | null |
现在,希望统计每个clan的成员数,并将其写入到clans表对应的membership列中,SQL语句如下:
UPDATE clans a
INNER JOIN(
SELECT clans.clan_id, COUNT(users.clan_id) AS membership
FROM clans
LEFT JOIN users ON clans.clan_id=users.clan_id
GROUP BY clans.clan_id) c ON a.clan_id=c.clan_id SET a.membership=c.membership
综合运用了UPDATE、SELECT、GROUP BY和JOIN,其中JOIN后跟着的括号SELECT clans.clan_id, COUNT(users.clan_id) AS membership FROM clans LEFT JOIN users ON clans.clan_id=users.clan_id GROUP BY clans.clan_id
的查询结果如下表:
clan_id | membership |
---|---|
1 | 1 |
2 | 2 |
3 | 1 |
通过GROUP BY,将这个表的membership列写入到clans表的目标列中,最终完成要求。
欢迎来到Yari的网站:yar2001 » MySQL UPDATE、SELECT、GROUP BY和JOIN的超级联用