我试着通过MySQL和PHP获取上周排名最靠前的照片。我发现贝叶斯公式可能就是我所需要的,但我一直在弄它,但却一无所获。
下面的代码不返回任何错误,它只返回一个'0‘。这就是为什么我一点也没有。
$bayesian_algo = "SELECT
photo_id,
(SELECT count(photo_id) FROM photo_ratings) /
(SELECT count(DISTINCT photo_id) FROM photo_ratings) AS avg_num_votes,
(SELECT avg(rating) FROM photo_ratings) AS avg_rating,
count(photo_id) as this_num_votes,
avg(rating) as this_rating
FROM photo_ratings
WHERE `date` > '$timeframe'
GROUP BY photo_id";
$bayesian_info = $mysqli->query($bayesian_algo);
$all_bayesian_info = array();
while($row=$bayesian_info->fetch_assoc()) array_push($all_bayesian_info,$row);
list($photo_id,$avg_num_votes,$avg_rating,$this_num_votes,$this_rating) = $all_bayesian_info;
$photo_id = intval($photo_id);
$avg_num_votes = intval($avg_num_votes);
$avg_rating = intval($avg_rating);
$this_num_votes = intval($this_num_votes);
$this_rating = intval($this_rating);
$bayesian_result = (($avg_num_votes * $avg_rating) + ($this_num_votes * $this_rating)) / ($avg_num_votes + $this_num_votes);
echo $bayesian_result; // 0??我的数据库如下所示:
photo_id | user_id | rating | date其中所有字段都存储为INTs (我将date存储为UNIX时间戳)。
我太累了,编码也不计后果,正常情况下,如果有错误消息(或任何消息),我至少可以得到更多信息,但是如果我使用var_dump($all_bayesian_info),我得到的数据不可能返回0。
发布于 2013-01-20 13:49:42
让我们在mysql查询本身中进行复杂的贝叶斯计算!
代码可以像这样重写:
$bayesian_algo_result = "SELECT *,
(((resultdata.avg_num_votes * resultdata.avg_rating) + (resultdata.this_num_votes * resultdata.this_rating)) / (resultdata.avg_num_votes + resultdata.this_num_votes)) AS bayesian_result
FROM
(
SELECT
photo_id,
(SELECT count(photo_id) FROM photo_ratings) /
(SELECT count(DISTINCT photo_id) FROM photo_ratings) AS avg_num_votes,
(SELECT avg(rating) FROM photo_ratings) AS avg_rating,
count(photo_id) as this_num_votes,
avg(rating) as this_rating
FROM photo_ratings
WHERE `date` > '$timeframe'
GROUP BY photo_id
) AS resultdata;
";
$bayesian_result_info = $mysqli->query($bayesian_algo_result);
//loop through the rows.
while($row = $bayesian_result_info->fetch_assoc()) {
list(
$photo_id,
$avg_num_votes,
$avg_rating,
$this_num_votes,
$this_rating,
$bayesian_result
) = $row;
echo 'Balesian rating for photo' . $photo_id . ' is: ' . $bayesian_result;
}注意:
http://sqlfiddle.com/#!2/d4a71/1/0
https://stackoverflow.com/questions/14420494
复制相似问题