1

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

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 = 玩家
回合的 ID = 已玩的回合(从 1 到 4)
已玩 = 如果用户玩过 = 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 语句来实现它?谢谢!

4

2 回答 2

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;

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

played = number of rounds played by the user status = number of rounds won by the user

You can easily calculate the number of lost rounds by substracting the two.

于 2013-04-07T22:38:08.143 回答
1

If I understand you correctly you can use conditional count like this

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

The query has not been tested

于 2013-04-07T22:38:16.033 回答