获取mysql中平均列的平均值

时间:2021-06-14 09:06:33

标签: php mysql codeigniter

我有一张表,用于存储餐厅的评分。如下图所示。

enter image description here

我试图获得所有这些列的平均值,我在其中取得了成功,但我也希望将所有这些平均值的平均值作为主要平均值。

我尝试了以下查询,但平均评分为 3,这是不准确的。我认为 mysql 正在向我返回最终结果的整数值。

return $this->db->select('((ambience + music + service + value_for_money + cleanliness + sanitary + view)/7) as rating, AVG(ambience) as ambience, AVG(music) as music, AVG(service) as service,AVG(value_for_money) as value_for_money, AVG(cleanliness) as cleanliness, AVG(sanitary) as sanitary, AVG(view) as view' )
        ->where('restaurant_id',$restaurantId)
        ->get('restaurant_ratings')
        ->row_array();

当我运行上述查询时,评分字段的平均值为 3。

enter image description here

实际结果是 3.42。

请帮助我了解我做错了什么以及可以做些什么来获得准确的结果。 谢谢

1 个答案:

答案 0 :(得分:3)

只需添加 AVG 即可计算评分:

$query = 
    'AVG((
        ambience + 
        music + 
        service + 
        value_for_money + 
        cleanliness + 
        sanitary + 
        view
    )/7) as rating, 
    AVG(ambience) as ambience, 
    AVG(music) as music, 
    AVG(service) as service,
    AVG(value_for_money) as value_for_money, 
    AVG(cleanliness) as cleanliness, 
    AVG(sanitary) as sanitary, 
    AVG(view) as view';

return $this->db
            ->select($query)
            ->where('restaurant_id',$restaurantId)
            ->get('restaurant_ratings')
            ->row_array();
相关问题