我在Mysql中有一个数据库,我想统计一个团队中有多少类型的玩家。我的问题是,即使团队中没有那种球员,我也想展示所有类型的球员。
让我向您展示数据表:
INSERT INTO typePlayer (id_typeplayer,type_player,id_race) VALUES
(57,"zombi",15),
(58,"necrofago",15),
(59,"tumulario",15),
(60,"Hobre Lobo",15),
(61,"Golem de Carne",15);
INSERT INTO teams (id_team, id_race) VALUES
(7,15);
INSERT INTO Players (id_player, id_typeplayer, id_team) VALUES
(1,60,7),
(2,60,7),
(3,58,7),
(4,58,7),
(5,59,7),
(6,59,7),
(7,57,7),
(8,57,7),
(9,57,7),
(10,57,7),
(11,57,7);
我希望有一个查询可以给我这个:
57,zombi,5
58,necrofago,2
59,tumulario,2
60,Hombre Lobo,2
61,Golem de Carne,0
我的问题是我无法显示最后一行(计数为空,因为球队没有该类型的球员)
我已经尝试过了,但结果很差:
SELECT tP.id_typeplayer,
count(p.id_typeplayer) cant,
p.id_team
FROM players p
JOIN typePlayer tP ON(tP.id_typeplayer=p.id_typeplayer)
WHERE (p.status='En activo'
OR p.status='Lesionado')
AND p.independiente='No'
AND p.zombificado='No'
AND p.id_team=7
AND tP.id_race=15
GROUP BY tP.id_typeplayer HAVING cant>=0
我会谢谢你的帮助
最佳答案
尝试使用此SQL,即使没有该类型的播放器,您也需要包含所有typePlayer
元组。如果typePlayer
表在左侧,则为左联接;如果typePlayer
表在右侧,则为右联接。
我实际上转到了您在sqlfiddle中提供的链接。您的typePlayer
表在右侧,因此我将其更改为右侧联接。结果SQL如下
SELECT tP.id_typeplayer,tp.type_player,
sum(if(p.id_team is null, 0,1)) cant,
p.id_team
FROM players p
RIGHT JOIN typePlayer tP ON(tP.id_typeplayer=p.id_typeplayer)
GROUP BY tP.id_typeplayer
您在评论中提到的另一件事是只有
id_team=7
,我认为您只需要在这样的where子句中过滤掉即可。SELECT tP.id_typeplayer,tp.type_player,
sum(if(p.id_team is null, 0,1)) cant,
p.id_team
FROM players p
RIGHT JOIN typePlayer tP ON(tP.id_typeplayer=p.id_typeplayer)
WHERE p.id_team=7 or p.id_team is null
GROUP BY tP.id_typeplayer