2

我试图通过 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

所有字段都存储为 INT(我将日期存储为 UNIX 时间戳)。

我很累并且鲁莽地编码,通常如果有错误消息(或任何东西!),我至少可以走得更远,但如果我var_dump($all_bayesian_info)返回 0,我就无法获得数据。

4

1 回答 1

2

让我们在 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;
}

笔记:

  • 这是一个有效的 sql fiddle:http ://sqlfiddle.com/#!2/d4a71/1/0

  • 我没有对您的公式进行任何逻辑更改。所以请确保你的公式是正确的。

  • 如果/当 UNIX 时间戳变为 64 位数据类型时,则必须使用 MySQL“bigint”来存储它们(用于“日期”列)。
于 2013-01-20T05:49:42.087 回答