2013-03-29 143 views
2

我正在爲我玩的人制作關於高爾夫的統計頁面。我試圖從數據庫中抽出我們收到小鳥的所有記分卡的次數(低於標準桿-1)。它確實拉出了每洞-1個,但是我注意到如果你在記分卡上有2只小鳥,它仍然只能算作1只小鳥而不是2只。我希望它繼續計數,所以如果有人得到9只小鳥,那麼總共增加了9個。只計算每行1的計數值

$query_p321 = "SELECT t1.*,COUNT(t1.player_id),t2.* FROM scorecards t1 LEFT JOIN courses t2 ON t1.course_id=t2.course_id 
WHERE t1.hole1<t2.hole1_par AND t1.hole1>t2.hole1_par-2 
    OR t1.hole2<t2.hole2_par AND t1.hole2>t2.hole2_par-2 
    OR t1.hole3<t2.hole3_par AND t1.hole3>t2.hole3_par-2 
    OR t1.hole4<t2.hole4_par AND t1.hole4>t2.hole4_par-2 
    OR t1.hole5<t2.hole5_par AND t1.hole5>t2.hole5_par-2 
    OR t1.hole6<t2.hole6_par AND t1.hole6>t2.hole6_par-2 
    OR t1.hole7<t2.hole7_par AND t1.hole7>t2.hole7_par-2 
    OR t1.hole8<t2.hole8_par AND t1.hole8>t2.hole8_par-2 
    OR t1.hole9<t2.hole9_par AND t1.hole9>t2.hole9_par-2 
    OR t1.hole10<t2.hole10_par AND t1.hole10>t2.hole10_par-2 
    OR t1.hole11<t2.hole11_par AND t1.hole11>t2.hole11_par-2 
    OR t1.hole12<t2.hole12_par AND t1.hole12>t2.hole12_par-2 
    OR t1.hole13<t2.hole13_par AND t1.hole13>t2.hole13_par-2 
    OR t1.hole14<t2.hole14_par AND t1.hole14>t2.hole14_par-2 
    OR t1.hole15<t2.hole15_par AND t1.hole15>t2.hole15_par-2 
    OR t1.hole16<t2.hole16_par AND t1.hole16>t2.hole16_par-2 
    OR t1.hole17<t2.hole17_par AND t1.hole17>t2.hole17_par-2 
    OR t1.hole18<t2.hole18_par AND t1.hole18>t2.hole18_par-2 
GROUP BY t1.player_id ORDER BY count(t1.player_id) DESC"; 
$result_p321 = mysql_query($query_p321); 
$number = 1; 
while ($row_p321 = mysql_fetch_array($result_p321)) { 
    $player_id2 = $row_p321["player_id"]; 
    } 
and so on.. 

你會注意到那裏的「-2」。這是採取減去2,因爲我不想記錄,如果人是2下。下一筆。任何幫助表示讚賞。謝謝。 哦,還有,需要使用GROUP BY,因爲我不想多次列出玩家名稱。只是想要它計數所有的小鳥。我想我的大問題是它不會超過每行1個。謝謝。

+0

您能否提供存儲信息的表的說明?您的查詢看起來非常複雜,相當容易出現問題。 –

+1

您需要一些括號... – MichaelRushton

+1

您正在尋找't1.hole1 t2.hole1_par-2',它會更簡單(並避免上面提到的丟失的括號)看起來對於't1.hole1 = t2.hole1_par-1'。但是,爲了回答根本問題,我認爲將'COUNT(t1.player_id)'改爲'COUNT(*)'會解決它。 – EvilBob22

回答

0

嘗試類似的東西:

SELECT t1.*, SUM(IF(t1.hole1 = t2.hole1_par-1,1,0) + 
     IF(t1.hole2 = t2.hole2_par-1,1,0) + 
     IF(t1.hole3 = t2.hole3_par-1,1,0) + 
     IF(t1.hole4 = t2.hole4_par-1,1,0) + 
     -- etc. 
     IF(t1.hole18 = t2.hole18_par-1,1,0)) AS birdies 
FROM scorecards t1 
LEFT JOIN courses t2 ON t1.course_id=t2.course_id 
GROUP BY t1.player_id 
ORDER BY birdies DESC 
+0

工作完美。非常感謝! – Rmurp006

+0

'IF(t1.hole1 NOT NULL && t1.hole1 = t2.hole1_par,1,0)'應該這樣做。別客氣。 – didierc

+0

美麗。再次感謝。 – Rmurp006

1

的問題是where條款。你需要做的比較的select子句中,以算來:

SELECT t1.*, 
     sum((t1.hole1 = t2.hole1_par - 1) + 
      (t1.hole2 = t2.hole2_par - 1) + 
      . . . 
      (t1.hole18 = t2.hole18_par - 1) 
     ) as birdies 
FROM scorecards t1 LEFT JOIN 
    courses t2 ON t1.course_id=t2.course_id 
GROUP BY t1.player_id 
ORDER BY birdies DESC 

這將使用MySQL的慣例,真正的是1和0虛假加數字0。使用標準SQL的備選公式是:

 sum((case when t1.hole1 = t2.hole1_par - 1) then 1 else 0 end) + 
+0

感謝您的幫助! – Rmurp006