INNER JOIN中的COUNT()行值

时间:2015-01-20 23:44:34

标签: mysql sql count inner-join

我需要通过计算玩家ID出现在另一张桌子上的次数来计算玩家玩过的游戏数量,这是我一直在玩的代码:

SELECT players.playerID, players.fName, players.lName, matches.playerID, COUNT(matches.playerID) AS 'gamesPlayed'
        FROM players
        INNER JOIN matches
        ON matches.playerID = players.playerID
        WHERE players.playerID=matches.playerID
        ORDER BY gamesPlayed"

目前有2名选手参加了2场比赛。

当前代码返回1名玩过4场比赛的玩家。

我正在尝试获取COUNT(matches.playerID)以仅返回players.playerID = matches.playerID的匹配。

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:2)

您需要GROUP BY

SELECT p.playerID, p.fName, p.lName, COUNT(*) AS gamesPlayed
  FROM players p INNER JOIN matches m
    ON p.playerID = m.playerID
 GROUP BY p.playerID, p.fName, p.lName
 ORDER BY gamesPlayed

如果你想要玩过零游戏的玩家,那么:

SELECT p.playerID, p.fName, p.lName, COUNT(m.playerID) AS gamesPlayed
  FROM players p LEFT JOIN matches m
    ON p.playerID = m.playerID
 GROUP BY p.playerID, p.fName, p.lName
 ORDER BY gamesPlayed

我在上面使用COUNT(m.playerID)而不是COUNT(*)的原因是因为COUNT(*)在这种情况下总是至少有一个,而COUNT(m.playerID)如果是NULL则可以为零唯一匹配的值为{{1}}。

答案 1 :(得分:0)

首先:您的查询缺少GROUP BY,第二个 - 请检查COUNT接受的参数(在此查询中它与COUNT(*)没有区别) - zerkms