如何在 Codeigniter 中使用 JOIN 从两个表中获取 AVERAGE

How to get AVERAGE from two tables using JOIN in Codeigniter

我有一个 table 结构,如下所示,我想获得每个 post 的平均评分,为此我正在编写以下查询以加入和获取记录,但它给出了语法错误:

$this->db->select($query = $this->db->query('SELECT * FROM post,AVG(`rating`) AS `avg_rating` JOIN review ON `post`.`id` = `review`.`post_id`');

发现两个问题:

  • 您的代码不正确。 Codeigniter 在创建查询时需要某种格式,请按照 manual here 更深入地了解。

  • 你得到的是平均评分,但你没有分组,因此以一个结果结束,而不是每个结果一个结果 post。

这就是我重写你的模型方法的方式:

function getRatingInfo(){
    $this->db->select("*, AVG(rating) AS avg_rating");
    $this->db->from("post p");
    $this->db->join("review r", "p.id=r.post_id");
    $this->db->group_by("post_id");
    $query = $this->db->get();
    return $query->result();
}

你不使用 group by 并像这样执行使用 $this->db->query(" your sql");

$this->db->query('select rating.post_id,avg(rating.rating) as `avg_rating` from rating,post where rating.post_id=post.id group by rating.post_id');