获取 mysql 中平均列的平均值

Get average of average columns in mysql

我有一个 table 来存储餐厅的评级。如下图所示。

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

我尝试了以下查询,但我得到的平均评分为 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 作为评分字段的平均值。

实际结果为 3.42。

请帮助我理解我做错了什么,以及如何才能获得准确的结果。 谢谢

只需添加 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();