将此MySQL查询组合起来更高效

时间:2015-04-13 08:29:14

标签: php mysql

我最近开发了这个网站,玩家可以在我的网站上排名玩某些街机游戏。我遇到的一个问题是使用了太多的SQL查询。我的页面加载时间受到会员注册的极大影响。我意识到我一直在使用的一些代码可能需要修改。这是我的第一个问题。

<?php

$time = time();

     $query5 = $db->query("SELECT playeruid , playeruid AS player_id, (
(
    SELECT COALESCE(sum(player1points),0) 
    FROM  `mybb_matches` 
    WHERE player1uid = player_id AND gid = '1' AND timestamp < $time AND winneruid is NOT NULL )
+
(
    SELECT COALESCE(sum(player2points),0) 
    FROM  `mybb_matches` 
    WHERE player2uid = player_id AND gid = '1' AND timestamp < $time AND winneruid is NOT NULL )
+
(
    SELECT SUM( rank ) 
    FROM  `mybb_matchesgame` 
    WHERE playeruid = player_id AND gid = '1' LIMIT 1 )
)

 AS points
 FROM mybb_matchesgame WHERE gid = '1'
 ORDER BY points DESC LIMIT 1");         
while($row = mysqli_fetch_array($query5))

{
echo "
<div class=\"fluidbox\"><a href='member.php?action=profile&uid=$player[uid]'>$player[username]</a>";

} 
 ?>

<?php

$time = time();

     $query5 = $db->query("SELECT playeruid , playeruid AS player_id, (
(
    SELECT COALESCE(sum(player1points),0) 
    FROM  `mybb_matches` 
    WHERE player1uid = player_id AND gid = '2' AND timestamp < $time AND winneruid is NOT NULL )
+
(
    SELECT COALESCE(sum(player2points),0) 
    FROM  `mybb_matches` 
    WHERE player2uid = player_id AND gid = '2' AND timestamp < $time AND winneruid is NOT NULL )
+
(
    SELECT SUM( rank ) 
    FROM  `mybb_matchesgame` 
    WHERE playeruid = player_id AND gid = '2' LIMIT 1 )
)

 AS points
 FROM mybb_matchesgame WHERE gid = '2'
 ORDER BY points DESC LIMIT 1");         
while($row = mysqli_fetch_array($query5))

{
echo "
<div class=\"fluidbox\"><a href='member.php?action=profile&uid=$player[uid]'>$player[username]</a>";

} 
 ?>

如您所见,代码重复但后来用于查找其他GID。我做了4次以找到所有独特的GID。但是,我意识到,这在网站加载时间的几秒钟内已经痛苦地添加了。我意识到我需要将这些代码组合在一起,我可以用它来查找所有唯一的GID。

我遇到的方法之一是截然不同的。但是,我无法让它工作。这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

问题是您多次查询数据库时可能没有必要,因为您可以通过较少的“子查询”获得结果 E.g。

(SELECT Coalesce(Sum(player1points), 0) 
    FROM   `mybb_matches` 
    WHERE  player1uid = player_id 
           AND gid = '1' 
           AND timestamp < $time 
           AND winneruid IS NOT NULL) 
+ (SELECT Coalesce(Sum(player2points), 0) 
    FROM   `mybb_matches` 
    WHERE  player2uid = player_id 
           AND gid = '1' 
           AND timestamp < $time 
           AND winneruid IS NOT NULL) [...]

可以“简化”到这样的事情。我不知道你的架构,这只是一个快速的建议。这甚至可能更慢或不起作用,因为它可能存在一些错误:D

(SELECT (Sum(player1points)+Sum(player2points)+Sum(rank)) as total 
  FROM   `mybb_matches` 
  LEFT OUTER JOIN `mybb_matchesgame`
     ON playeruid = player_id
    AND gid = '1'
    AND timestamp < $time
    AND winnderuid IS NOT NULL
    AND ( player1uid = player_id OR player2uid = player_id ))