平均评级然后使用 codeigniter 加入 2 个表
Average rating then join 2 tables using codeigniter
我需要一些帮助,我有 2 个 table,像这样
table a table b
+-------+---------+ +---+--------+--------+
| no | name | | NO| cafe | rating |
+-------+---------+ +---+--------+--------+
| 1 | cafe a | | 1 | cafe a | 5 |
| 2 | cafe b | | 2 | cafe a | 4 |
| 3 | cafe c | | 3 | cafe b | 4 |
| 4 | cafe b | 3 |
| 5 | cafe a | 2 |
我想要的结果
+-------+---------+-------+
| no | name |rating |
+-------+---------+-------+
| 1 | cafe a | 4.5 |
| 2 | cafe b | 3.5 |
| 3 | cafe c | 2 |
有人可以告诉我如何使用 codeigniter 解决它,或者提供模型参考。谢谢
您似乎想要 join
和聚合:
select a.*, b.rating
from (select name, avg(b.rating) as rating
from b
group by name
) b join
a
on a.name = b.name;
请注意,某些数据库会进行整数平均,因此您可能需要 avg(b.rating * 1.0)
。
我需要一些帮助,我有 2 个 table,像这样
table a table b
+-------+---------+ +---+--------+--------+
| no | name | | NO| cafe | rating |
+-------+---------+ +---+--------+--------+
| 1 | cafe a | | 1 | cafe a | 5 |
| 2 | cafe b | | 2 | cafe a | 4 |
| 3 | cafe c | | 3 | cafe b | 4 |
| 4 | cafe b | 3 |
| 5 | cafe a | 2 |
我想要的结果
+-------+---------+-------+
| no | name |rating |
+-------+---------+-------+
| 1 | cafe a | 4.5 |
| 2 | cafe b | 3.5 |
| 3 | cafe c | 2 |
有人可以告诉我如何使用 codeigniter 解决它,或者提供模型参考。谢谢
您似乎想要 join
和聚合:
select a.*, b.rating
from (select name, avg(b.rating) as rating
from b
group by name
) b join
a
on a.name = b.name;
请注意,某些数据库会进行整数平均,因此您可能需要 avg(b.rating * 1.0)
。