我试图用php mysql_query在mysql中平均几行,但我似乎遇到了一些问题..
$ratingsql = "SELECT AVG(Rating) AS RatingAverage FROM wp_reciperatings;";
$ratingresult = mysql_query($ratingsql);
// Print out result
while($ratingrow = mysql_fetch_array($ratingresult)){
echo "The average rating is ".$ratingrow['AVG(RatingAverage)'];
echo "<br />";
我的表看起来像..
ID Rating
_______________________
| 1 | 1 |
| 1 | 2 |
| 1 | 5 |
评分从1-5,5最佳。我能够将mysql查询打入我的sql客户端,它工作正常,怎么会在我的页面上不起作用?
另外,我如何计算一个id的平均值?
非常感谢!非常感谢。
答案 0 :(得分:2)
改变这个 -
echo "The average price of is ".$ratingrow['AVG(rating)'];
到此 -
echo "The average price of is ".$ratingrow['RatingAverage '];
由于您为结果列提供了别名,因此您需要在PHP中使用该别名来显示数据。
对一个ID的平均值的查询将是 -
SELECT AVG(Rating) AS RatingAverage
FROM wp_reciperatings
WHERE ID = '1'; // replacing with ID as needed