本文介绍了如何使用Codeigniter查询获得每种产品的平均评级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个评分表,其中列出了用户给定的每种产品的评分,我正在检索所有评分记录,但同时我想获得基于每种产品的平均评分,但我无法获得输出量

I have rating table which have rating for every product given by user, I am retrieving all rating records, but at the same time I want to get avg rating based on per product but I am unable to get ouptput

查询:

$this->db->select('ratings.*');
$this->db->select('select AVG(ratings) as avg_rating from ratings group by product_id');
$this->db->from('ratings');
$this->db->join('users','users.id=ratings.user_id');
$this->db->get()->result();

评分表

id   user_id product_id  rating  

1      4         1         4
 
2      5         2         4

3      6         1         2


4      7         4         4

预期输出:

id   user_id product_id  rating          avg rating

1      4         1         4               3
 
2      5         2         4               4

3      6         1         2               3


4      7         4         4               4

推荐答案

使用左连接和select作为平均值,从表 ratings 中获取数据.

get data from table ratings, using a left join with select for the average.

join()函数Codeigniter允许您编写选择部分而不是表名,但是需要将其放在括号中:

the join() function of Codeigniter allows you to to write a select part instead of the table name, but you need to place it into parenthesis:

$this->db->select('t1.*, t2.avg_rating, t3.*');
$this->db->from('ratings t1');
$this->db->join('
                  (select product_id, avg(rating) as avg_rating 
                   from ratings 
                   group by product_id)  t2','t2.product_id=t1.product_id','left'
                );
$this->db->join('users t3','t3.id=t1.user_id','left'); 
$this->group_by('t1.userid')
$this->db->get()->result();

生成:

SELECT t1.*, t2.avg_rating, t3.*
FROM ratings t1
left join 
        (select product_id, avg(rating) as avg_rating from ratings group by product_id)  t2 
    on t2.product_id=t1.product_id
left join users t3
    on t1.user_id = t3.id
group by t1.user_id

并按预期输出.

这篇关于如何使用Codeigniter查询获得每种产品的平均评级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 09:45