2017-04-12 160 views
0

我正在製作一個web應用程序來創建錦標賽,正如我在這個項目過程中學到的PHP一樣,所以我的技能可能不是最好的。結合兩個mysql組查詢

我在我的數據庫day2_semifinalday2_additional中有一個標識符,它基本上標識了半決賽的類型。

所以我的第一個查詢是:

$numberquery = mysql_query(" 
SELECT * 
FROM tourneyplayers 
INNER JOIN results 
    on (resultid=r_id) 
INNER JOIN players 
    ON (p_id=playerid) 
INNER JOIN tourneys 
    on (T_Id=tourneyid) 
WHERE tourneyid='$tourneyid' and 
     in_day2 = 1 and 
     day2_semifinal IS NOT NULL 
GROUP BY day2_semifinal 
ORDER BY agegroupid",$connection); 

這將讓我所有的半決賽組,我會在它們之間迭代和查詢組中的所有玩家:

$semigroup = $group['day2_semifinal']; 
$playerQuery = mysql_query(" 
SELECT * 
FROM tourneyplayers 
INNER JOIN results 
    on (r_id=resultid) 
INNER JOIN players 
    on (p_id=playerid) 
WHERE tourneyid='$tourneyid' AND 
     day2_semifinal = '$semigroup' and 
     in_day2 = 1 
ORDER BY day2startplace",$connection); 

現在我後創建了表格並回應了所有來自玩家查詢的數據day2_semifinal,我運行了另一個查詢:

$numberquery = mysql_query("SELECT * FROM tourneyplayers INNER JOIN results on (resultid=r_id) INNER JOIN players ON (p_id=playerid) WHERE tourneyid='$tourneyid' and in_day2 = 1 and day2_additional_nosemi IS NOT NULL AND day2_additional_nosemi <> 0 GROUP BY day2_additional_nosemi ORDER BY agegroupid",$connection); 

這與第一個非常相似,唯一不同的是day2_semifinal標識符已更改爲day2_additional。該查詢後,我會再,遍歷day2_additional_nosemi組和查詢他們的內部玩家:

$additionalgroup = $group['day2_additional_nosemi']; 
$playerQuery = mysql_query("SELECT * FROM tourneyplayers INNER JOIN results on (r_id=resultid) INNER JOIN players on (p_id=playerid) WHERE tourneyid='$tourneyid' AND day2_additional_nosemi = '$additionalgroup' and in_day2 = 1 ORDER BY day2startplace",$connection); 

現在這個工作,但這個由agegroupid創建了排序問題,因爲第一個查詢他們的訂單,但只適用於day2_semifinal(並且我希望day2_additional玩家與day2_semifinal一起訂購)。如果我運行另一個查詢,以前的數據已被回顯,並排序不正確。我如何連接兩個$numberquery查詢以便選擇後面的玩家呢?

+0

刪除mysql_ *。現在爲了安全起見,從php7中刪除,使用mysqli_或pdo –

+0

我將在下一個項目中繼續討論這個問題,我目前仍在學習,而且我正在修改的區域不是公開的。 – Banana

+0

您的第一個查詢無效,因爲您在使用「GROUP BY」時選擇所有列。你究竟在第一個查詢中想要聚合什麼? –

回答

1

我回答我自己的問題,因爲我想出了一個辦法來做到這一點。我做了,除去來自查詢ORDER BY並創建了級聯兩個與UNION一個新的查詢:

SELECT * FROM (
SELECT * 
FROM tourneyplayers as tp1 
INNER JOIN results as r1 
    on (tp1.resultid=r1.r_id) 
INNER JOIN players as p1 
    ON (p1.p_id=tp1.playerid) 
WHERE tp1.tourneyid=96 and 
     tp1.in_day2 = 1 and 
     r1.day2_semifinal IS NOT NULL 
GROUP BY r1.day2_semifinal 
UNION ALL 
SELECT * 
FROM tourneyplayers as tp2 
INNER JOIN results as r2 
on (tp2.resultid=r2.r_id) 
INNER JOIN players as p2 
ON (p2.p_id=tp2.playerid) 
WHERE tp2.tourneyid=96 and 
tp2.in_day2 = 1 and 
r2.day2_additional_nosemi IS NOT NULL AND 
r2.day2_additional_nosemi <> 0 
GROUP BY r2.day2_additional_nosemi 
) t ORDER BY t.agegroupid;