0

我有两个具有以下结构的表:

表 1:显示玩家尝试的次数。

Player_id, n_tries, date

表 2:显示球员击球次数。

Player_id, n_hits, date

最后,我希望获得玩家今天的命中百分比(尝试次数与命中次数)以及今天和一周前之间点击次数的增加/减少。我希望结果按(今天)命中后代的百分比排序。因此,例如,如果我们有一个 id = 1 的玩家和一个 id = 2 的玩家,使用以下数据:

表格1:

1, 10, "2012-10-14"
2, 13, "2012-10-14"
1, 20, "2012-10-7"
2, 15, "2012-10-7"

表 2:

1, 5, "2012-11-14"
2, 10, "2012-11-14"
1, 0, "2012-11-7"
2, 3, "2012-11-7"

我最终需要证明这一点:

Player_id,命中率(今天),命中率差异(今天与一周前)

2            77%       +233%
1            50%       +100% (actually is infinite -> (5 - 0)/0 )

我有从两个表中获取值的查询:

第一个表 - 尝试次数:

SELECT player_id, date, sum(n_tries) 
FROM player_tries 
WHERE (d_date = CURDATE() OR d_date = DATE_SUB(CURDATE(), INTERVAL 7 DAY))
GROUP BY date, player_id
ORDER BY player_id, date

我做了一个 sum(n_tries) 因为玩家可以在特定的一天进行多行尝试。

第二个表 - 命中数:

SELECT player_id, date, sum(n_hits) 
FROM player_hits
WHERE (d_date = CURDATE() OR d_date = DATE_SUB(CURDATE(), INTERVAL 7 DAY))
GROUP BY date, player_id
ORDER BY player_id, date

所以,我的问题是:如果从第一个查询中我得到一个如下所示的结果列表:

Player_id, date,         n_tries
1         2012-11-07        20
1         2012-11-14        10
2         2012-11-07        15
2         2012-11-14        13

从第二张桌子我得到这个:

 Player_id, date,         n_hits
    1         2012-11-07        0
    1         2012-11-14        5
    2         2012-11-07        3
    2         2012-11-14        10

能够混合这些结果并能够拥有某种按命中率(今天)排序的结构的最佳方法是什么?

4

1 回答 1

0

Select hits from today and a week ago:

select h1.player_id, `h1.date`,
       sum(h1.hits) as hits_today,
       sum(h2.hits) as hits_last_week
from player_hits h1
left join player_hits h2 on h2.player_id = h1.player_id
                            and `h2.date` = date_sub(`h1.date`, interval 7 days)
group by h1.player_id, `h1.date`;

If you only want rows when there is a corresponding entry a week before, then replace the left join with an inner join.

The select for the tries table looks equivalent.

First select your results into arrays with player_id as keys.

$hits_array = array();
$result = mysqli_query(...);
while ($row = mysqli_fetch_assoc($result)) {
    $player = $row['player_id'];
    $hits_array[$player] = $row['hits'];
}

You do the same with the tries table.

Now you can join the two arrays on the player_id keys:

foreach ($hits_array as $player => $hits) {
    echo "$player " . ($hits / $tries[$key]) . "\n";
}
于 2012-11-14T11:24:13.627 回答