0

是否有适当的方法来做到这一点。我想计算一个表的平均评分并同时更新另一个表中的结果。我是 PHP 和 MYSQL 的新手,我将不胜感激

$query=mysql_query("INSERT INTO review (username, restaurant, rating, review) VALUES ('$username','$restaurant','$rating','$review')");
if($query)
{
    $avg_query="SELECT ROUND(AVG(rating),0) FROM review WHERE name =\"$restaurant\"";
    $avg_result=mysql_query($avg_query);
    $avg_row=mysql_fetch_array($avg_result);
    $rating=$row['ROUND(AVG(rating),0)'];
    if($avg_result)
    {   
        $update_query= "UPDATE restaurant SET rating=\"$rating\" WHERE name =\"$restaurant\"";
        $update_result=mysql_query($update_query);
    }
}
else
{
}

谢谢!

4

3 回答 3

0
UPDATE restaurant 
SET rating= (SELECT ROUND(AVG(rating),0) FROM review WHERE name ='$restaurant')
WHERE name ='$restaurant'
于 2012-08-04T06:29:58.683 回答
0

另一种选择是使用 mysql trigger。例如(不要让我拘泥于语法):

CREATE TRIGGER after_insert_review
AFTER INSERT ON review
FOR EACH ROW
BEGIN
    UPDATE restaurant 
    SET rating = (SELECT ROUND(AVG(rating),0) FROM review WHERE name = NEW.restaurant)
    WHERE name = NEW.restaurant;
END

正如其他人所提到的,再次使用PDOMySQLi

于 2012-08-04T06:47:23.493 回答
0

我会像这样将两者合二为一:

$query=mysql_query("INSERT INTO review (username, restaurant, rating, review) VALUES ('$username','$restaurant','$rating','$review')");
if($query)
{
    $avg_query="UPDATE restaurant a SET rating=(SELECT ROUND(AVG(rating),0) FROM review WHERE name =a.name) WHERE name ='".$restaurant."'";
    $avg_result=mysql_query($avg_query);
}
else
{
}

话虽如此,您应该转而使用 PDO 或 mysqli,因为这些mysql_*功能已贬值。

于 2012-08-04T06:31:23.457 回答