所以我是sql的初学者,我遇到了一个问题,我不知道如何检查哪些玩家有多个团队。
制作一张桌子后:
CREATE TABLE TEAM(TeamID varchar(10),
PlayerID varchar(10) REFERENCES "Player" ("playerID"),
TeamName varchar(15));
然后是值:
INSERT INTO Team VALUES ('t001', 'p001','teamname1');
INSERT INTO Team VALUES ('t001', 'p002','teamname1');
INSERT INTO Team VALUES ('t002', 'p003','teamname2');
INSERT INTO Team VALUES ('t002', 'p002','teamname2');
如您所见:玩家2拥有更多团队而其他人只有一支团队。但是我怎么写这个可以看一下呢?
答案 0 :(得分:1)
您可以使用以下查询获取计数:
Select playerId,count(TeamId) from TEAM group by playerId having count(teamId)>=1
答案 1 :(得分:0)
Select COUNT(PlayerId)
from Team
where PlayerId = 'some Id';
这将返回玩家参与的团队数量。
答案 2 :(得分:0)
多种解决方案取决于您想要的内容
团队中所有球员的列表以及他们所在的球队数量
Select playerId,count(*)
from TEAM
group by playerId
ORDER BY count(*) DESc
| PlayerID | count(*) |
|----------|----------|
| p002 | 2 |
| p001 | 1 |
| p003 | 1 |
只有几支球队内的球员
SELEcT playerId,count(*)
FROM TEAM
GROUP BY playerId
HAvING count(*) > 1
ORDER BY count(*) DESc
| PlayerID | count(*) |
|----------|----------|
| p002 | 2 |
团队中的玩家以及他们所在的团队
SELEcT playerId,count(*) , GROUP_concat(Teamname) AS teams
FROM TEAM
GROUP BY playerId
ORDER BY count(*) DESc
| PlayerID | count(*) | teams |
|----------|----------|---------------------|
| p002 | 2 | teamname1,teamname2 |
| p001 | 1 | teamname1 |
| p003 | 1 | teamname2 |
此外,如果您需要所有玩家,即使他们不在团队中,您也应该使用FROM Players LEFT JOIN Teams
进行相同的查询,因为您没有显示您的玩家表格,所以我不会进行更多转换