How to get avg rating per product using codeigniter query?

戏子无情 提交于 2021-01-27 12:53:31

问题


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

Query :

$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();

Rating table

id   user_id product_id  rating  

1      4         1         4
 
2      5         2         4

3      6         1         2


4      7         4         4

Expected output:

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

回答1:


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

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();

generates:

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

and outputs as you expect.




回答2:


When Queries get complicated i like to use query instead of query builder. You could do this:

$this->db->query('select r.*,(select round(sum(r2.rating)/count(*),0) from ratings r2 where r2.product_id = r.product_id ) as 'avg rating' from ratings r')->result();


来源:https://stackoverflow.com/questions/63509229/how-to-get-avg-rating-per-product-using-codeigniter-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!