我有2个SELECT查询,一个用于检索团队,另一个用于计算该团队中有多少玩家。如何将计数查询添加到第一个数据选择查询?我已经尝试过工会,但由于它们没有相同的列数而无法工作。
SELECT Subteams.id, Teams.name, Games.name as 'game'
FROM Subteams, Games, Teams
WHERE Subteams.gameId = Games.id
AND Subteams.teamId = Teams.id
SELECT COUNT(Players.subTeamId) as 'count'
FROM Subteams, Games, Teams, Players
WHERE Subteams.gameId = Games.id
AND Subteams.teamId = Teams.id
AND Players.subTeamId = Subteams.id
ORDER BY Players.id
答案 0 :(得分:4)
只需将其他表中的列添加到COUNT()
查询。
SELECT Subteams.id, Teams.name, Games.name as game, COUNT(Players.subTeamId) as 'count'
FROM Subteams
JOIN Games ON Subteams.gameId = Games.id
JOIN Teams ON Subteams.teamId = Teams.id
LEFT JOIN Players ON Players.subTeamId = Subteams.id
GROUP BY Subteams.id
ORDER BY Subteams.id
我还使用了LEFT JOIN
,因此对于没有玩家的球队,您将获得0
。