MYSQL - 数轮

时间:2013-04-07 22:28:52

标签: mysql count inner-join

我得到了这个声明(到目前为止)的竞赛剧本:

SELECT COUNT(round) AS runden, COUNT(status) AS status FROM rounds AS r INNER JOIN player AS p ON r.playerID = p.id WHERE r.playerID = <ID>"  

此表保存特定用户播放的所有回合。 如果用户参与回合,则会在此表中写入:

id = id
playerId =玩家的身份
round =播放的轮次(从1到4)
play =如果用户播放= = 1,如果不是= 0
status =如果用户赢了这一轮= 1,如果不是= 0

现在我需要的是所有围绕状态值= 1或状态= 0的值。所以我需要总赢得的轮次和丢失轮次。

显示它:

function getRoundsByPlayer($playerId) {
        $sql = "
        SELECT COUNT(round) AS runden, COUNT(status) AS status FROM rounds AS r INNER JOIN player AS p ON r.playerID = p.id WHERE r.playerID = :playerId";
        try {
            $db = self::getConnection();
            $stmt = $db->prepare($sql);
            $stmt->bindParam("playerId", $playerId);
            $stmt->execute();
            $player = $stmt->fetch(PDO::FETCH_LAZY);
            $db = null;
            return $player;
        } catch(PDOException $e) {
            echo $e->getMessage();
        }
    }

$runden = $helper->getRoundsByPlayer($row['id']);  

和HTML:

...  
<td><?php echo $runden->runden; ?></td>  
...  

如何通过不使用第二个或第三个SQL语句来实现它?谢谢!

2 个答案:

答案 0 :(得分:1)

使用以下SQL语句(未测试):

SELECT SUM(played) AS played
       SUM(status) AS status
FROM rounds AS r
INNER JOIN player AS p
ON r.playerID = p.id
WHERE r.playerID = :playerId
GROUP BY r.playerID;

这应该为您提供以下信息:

  

播放=用户播放的轮次数   status =用户赢得的回合数

您可以通过减去两者来轻松计算丢失的轮数。

答案 1 :(得分:1)

如果我理解正确,你可以像这样使用条件计数

SELECT SUM(CASE WHEN r.status = 1 THEN 1 ELSE 0 END) AS won_rounds,
       SUM(CASE WHEN r.status = 0 THEN 1 ELSE 0 END) AS lost_rounds
  FROM rounds AS r INNER JOIN 
       player AS p ON r.playerID = p.id 
 WHERE r.playerID = <ID> AND r.played = 1
 GROUP BY r.playerID

查询尚未经过测试