结合两个mysql组查询

时间:2017-04-12 06:25:55

标签: php mysql

我正在制作一个网络应用程序来创建比赛,因为我在这个项目的过程中学习了PHP,所以我的技能可能不是最好的。

我的数据库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中的玩家(并且我希望{{1}玩家与day2_additional一起订购。如果我运行另一个查询,之前的数据已经被回显,并且排序不正确。我如何连接两个day2_semifinal查询以便选择跟在他们后面的玩家?

1 个答案:

答案 0 :(得分: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;