我正在努力寻找名字为'杰克'的玩家的身份以及他们玩过的游戏数量:
Select p.id, count(*) as numOfGamePlayed
from player p, game g
where p.name = 'Jack' and p.id = g.id
group by p.id;
问题是,这只会列出至少玩过一场比赛的球员名称杰克。我怎样才能列出那些没玩过任何游戏的人?
编辑:对于那些玩家,numOfGamePlayed必须为0.如果我这样做
Select p.id, count(*) as numOfGamePlayed
from player p LEFT JOIN game g ON p.id = g.id
where p.name = 'Jack'
group by p.id;
那些没有玩任何游戏的玩家仍会将numOfGamePlayed显示为1
答案 0 :(得分:4)
停止为初学者使用隐式联接。无论如何,这是一个坏习惯。然后你可以这样做:
Select p.id, count(g.id) as numOfGamePlayed
from player p
LEFT JOIN game g
ON p.id = g.id
where p.name = 'Jack'
group by p.id;
答案 1 :(得分:0)
你需要玩家和游戏之间的外部联接
SELECT p.ID,
COUNT(*) AS numOfGamePlayed
FROM player p
LEFT OUTER JOIN game g
ON p.id = g.id
WHERE p.name = 'Jack'
GROUP BY p.ID;
答案 2 :(得分:0)
SELECT p.id, count(*) as numOfGamePlayed
FROM player p
LEFT JOIN game g ON g.id = p.id
WHERE p.name = 'Jack'
--AND g.id IS NULL
GROUP BY p.id;
答案 3 :(得分:0)
你必须做count(game.PlayerId)而不是count(*)
select p.PNAME, g.gameplayed
from player p
left outer join game g
ON p.pid = g.pid;
Select p.pid, count(g.pid) as numOfGamePlayed
from player p
LEFT JOIN game g
ON p.pid = g.pid
where p.pname = 'Jack'
group by p.pid;