2013-04-07 69 views
1

我得到了這個聲明(到目前爲止)的比賽腳本:MYSQL - 計數輪

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 =玩家
圓=所播放的圓(從1到4)
起到=如果Id的如果不是= 0,則用戶播放= 1
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語句實現它?謝謝!

回答

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 

查詢尚未經過測試

+0

工程!謝謝! :) – Marek123 2013-04-07 22:44:14

+0

你當然歡迎:D快樂編碼。 – peterm 2013-04-07 22:44:48

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; 

這應該爲您提供以下信息:

起到=用戶 狀態=號碼打輪數的通過減去兩個用戶

可以方便地計算丟失的回合數輪贏了。

+0

不幸的是,這並不爲我工作。一些錯誤正在發生。但是,謝謝。我看到與正在爲我工​​作的peterm的答案有相似之處。 – Marek123 2013-04-07 22:43:34