2014-06-30 63 views
1

我試圖創建所有時間在幻想足球聯賽中進行頭對頭的比賽。我使用了兩個單獨的查詢,並使用兩個獨立的while循環來獲取數據。我希望我可以用IF聲明來比較兩者,但是沒有。比較來自2個循環的值(PHP MYSQL)

我的查詢如下:

$query5 = "SELECT *, SUM(POINTS) "; 
    $query5 .= " FROM SCHEDULE"; 
    $query5 .= " WHERE owner = 'DUSTIN'"; 
    $query5 .= " AND OPPONENT = 'LEE'"; 
    $query5 .= " GROUP BY WEEK "; 
    $result5 = mysqli_query($con, $query5); 

    $query6 = "SELECT *, SUM(POINTS) "; 
    $query6 .= " FROM SCHEDULE"; 
    $query6 .= " WHERE owner = 'LEE'"; 
    $query6 .= " AND OPPONENT = 'DUSTIN'"; 
    $query6 .= " GROUP BY WEEK "; 
    $result6 = mysqli_query($con, $query6); 

我的PHP:

while($row5 = mysqli_fetch_assoc($result5)){$row5 ["SUM(POINTS)"]; 
while($row6 = mysqli_fetch_assoc($result6)){$row6 ["SUM(POINTS)"]; 
if ($row5 ["SUM(POINTS)"] > $row6 ["SUM(POINTS)"]){ 
$win++; 
} 
else { 
$loss++; 
} 
} 
} 

該功能適用​​於$ ROW6,但$ ROW5它一遍又一遍地抓住了相同的號碼,而不是通過騎自行車陣列。

這裏是樣本數據:

YEAR WEEK OWNER OPPONENT POSITION PLAYER POINTS 
2008 1 Dustin Brandon RB Chris Johnson, Ten RB 19.7 
2008 1 Dustin Brandon QB Ben Roethlisberger, Pit QB 13.1 
2008 1 DUSTIN BRANDON D/ST Titans D/ST, Ten D/ST 17 
2008 1 DUSTIN BRANDON WR Roddy White, Atl WR 5.4 
2008 1 DUSTIN BRANDON RB Laurence Maroney, NE RB 6.1 
2008 1 BRANDON DUSTIN RB Adrian Peterson, Min RB 21.4 
2008 1 BRANDON DUSTIN RB Edgerrin James, Ari RB 15 
2008 1 BRANDON DUSTIN WR Larry Fitzgerald, Ari WR 9.1 
2008 1 BRANDON DUSTIN k Joe Nedney, SF K 4.5 
2008 1 BRANDON DUSTIN WR Chris Chambers, SD WR 11.4 

我需要他們在1星期加起來總共分達斯汀在1周內,並比較總積分爲Brandon和指示冠軍球隊的勝利。

+1

我敢肯定,你完全可以在SQL中做到這一點,但我不確定你想要完成什麼。 –

回答

1

下面的查詢將返回dustin,lee和總關係數的總和#。如果通過在同一周內比對手獲得更多積分來定義勝利。

該查詢假定兩位球員每週至少有一些積分。如果不是這種情況,則必須將內連接轉換爲完全連接。

SELECT 
    COUNT(CASE WHEN t1.points > t2.points THEN 1 END) dustin_win_count, 
    COUNT(CASE WHEN t2.points > t1.points THEN 1 END) lee_win_count, 
    COUNT(CASE WHEN t2.points = t1.points THEN 1 END) tie_count 
FROM 
    (SELECT WEEK, SUM(POINTS) points 
    FROM SCHEDULE WHERE 
    OWNER = 'DUSTIN' 
    AND OPPONENT = 'LEE' 
    GROUP BY WEEK) t1 
    JOIN (SELECT WEEK, SUM(POINTS) points 
    FROM SCHEDULE WHERE 
    OWNER = 'LEE' 
    AND OPPONENT = 'DUSTIN' 
    GROUP BY WEEK) t2 ON t1.WEEK = t2.WEEK 
+1

當我運行SQL時,這是完美的 - 謝謝!當我嘗試將它實現到PHP時,我收到了一個查詢錯誤,但是我會通過它進行處理。 – user3787390

+0

如何使用PHP/HTML顯示結果? – user3787390

+1

@ user3787390如果你需要更多的幫助,請打開一個新的問題 – FuzzyTree

0

我對複雜的mysql查詢的來龍去脈並不真實,但這與我用於計算我設計的投票系統中的投票相似。

$query = "SELECT SUM(POINTS)(CASE WHEN owner = 'DUSTIN' AND opponent = 'LEE' THEN 1 END) dustin, 
SUM(POINTS)(CASE WHEN owner = 'LEE' AND opponent = 'DUSTIN' THEN 1 END)lee, FROM SCHEDULE GROUP BY WEEK;"; 

while($row = mysql_fetch_assoc($query)) 
{ 
    if($row['dustin'] > $row['lee']) 
    { 
     $win++; 
    }else{ 
     $loss++; 
    } 
} 

它可能不是你的情況下工作,因爲我與COUNT代替SUM使用它,但它可能工作。如果它不讓我知道,我會嘗試別的。