复杂的mySQL查询用于获取三个不同的表进行比较

时间:2012-06-03 12:36:37

标签: php mysql sql

我需要创建非常困难的SQL查询,但我自己无法处理它。也许有人可以帮助我或建议一些不同的方法。

我有三张桌子: Table structures

我需要在页面上显示需要下一点的表格:

  • 将每个用户点与管理员点数(points.user_id = 1)进行比较
  • 如果积分相等,则用户根据积分保存日期与游戏保持日期之间的差异获得积分。如果点不同,则不添加任何点。
  • 我可以设置当上述两个日期之间的差异为例如用户可以获得多少分。 2天,3天等(如果(games.date - points.date = 2days {points = points * 2}或类似)
  • 比较发生在(games.date> now())
  • 之后

更新

$points = array();

$all_ifo = mysql_query("SELECT p.id, p.user_id, p.game_id, p.points, 
ABS(p.points - a.points) rating_diff, a.points, g.home, g.datetime, u.username
FROM points AS p 
JOIN points AS a ON p.game_id = a.game_id AND a.user_id = 1
JOIN games  AS g ON p.game_id = g.id
JOIN users  AS u ON p.user_id = u.id
WHERE p.user_id != 1 AND g.datetime < NOW();") or die(mysql_error());

while ($info = mysql_fetch_assoc($all_ifo)){
    $points['' . $info['username'] . ''] += $info['rating_diff'];
    echo $info['p.id'];
}
asort($points);

echo "<table class='tabelid'><th>Test</th>";
foreach ($points as $key => $value) {
    $i++;
    echo "<tr><td>".$i.".</td><td style='width:250px;'>" . 
    ucfirst($key) . "</td><td>" . $value . "</td></tr>";
}
echo "</table>";

更新2:

所以有人建议,对于点数我需要一个单独的表。但它很复杂:

Game saved in 25-45 min after game start - 1 point
Game saved in 0 - 24 min after game start - 2 points
Game saved in on the same day but before the game - 4 points 
Game saved in 1 day before - 6 points
Game saved in 2 days before - 8 points
..
Game saved in 15 days before - 34 points

那么有什么建议如何表格应该在以后轻松地实现它?以及rating_diff如何获得正确的点数?

更新3:

$points = array();

$all_ifo = mysql_query("SELECT x.*, d.*
  FROM Extra AS x
  JOIN (SELECT p.id, p.user_id, p.game_id, p.points, p.date, a.points adminpoints, g.home,
               g.datetime, u.username, TIMESTAMPDIFF(MINUTE, g.datetime, p.date) AS Offset
          FROM points AS p
          JOIN points AS a ON p.game_id = a.game_id AND a.user_id = 1
          JOIN games  AS g ON p.game_id = g.id
          JOIN users  AS u ON p.user_id = u.id
         WHERE p.user_id != 1
           AND g.datetime < NOW()
       ) AS d
    ON d.Offset >= x.LoOffsetFromGameTime
   AND d.Offset <  x.HiOffsetFromGameTime;") or die(mysql_error());

while ($info = mysql_fetch_assoc($all_ifo)){
    $points['' . $info['username'] . ''] += $info['Offset'];
    echo $info['p.id'];
    }

arsort($points);

echo "<table class='tabelid'><th>Test</th>";
foreach ($points as $key => $value) {
    $i++;
    echo "<tr><td>".$i.".</td><td style='width:250px;'>" . ucfirst($key) . "</td><td>" . $value . "</td></tr>";

}
echo "</table>";

对于输出,我得到保存时间和实际游戏时间之间的时差:

Test
1.  User1   1851
2.  User2   -502

但我不知道如何将它与Extra table进行比较,因此得到正确的分数。当然,只有当同一个game_id的分数(0,1或2)与管理员的分数(0,1或2)相同时,才应添加分数。

0 个答案:

没有答案
相关问题