1 回答
TA贡献1772条经验 获得超6个赞
使用左连接和选择平均值从表ratings获取数据。
Codeigniter 的join () 函数允许您编写选择部分而不是表名,但您需要将其放在括号中:
$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
并按照您的预期输出。
- 1 回答
- 0 关注
- 82 浏览
添加回答
举报