CodeIgniter:计算连接表的结果 [英] CodeIgniter: Counting results from a joined table

查看:107
本文介绍了CodeIgniter:计算连接表的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我知道如何连接两个表格,我想实际计算第二个表格中的活动记录数

Now I know how to join two tables, I'd like to actually count the number of rows in the second table with active records.

说,我有这两个表:

blog     comments
-------  ----------
id       id
title    blog_id
content  comment

否我想获取最后三个博客条目,并计算每个博客条目的评论数,所有在一个查询。我试过这样,但它不工作:

No I want to take the three last blog entries and count the number of comments per blog entry, all in one query. I tried something like this, but it doesn't work:

$this->db->select('*')
         ->from('blog')
         ->order_by('blog.id', 'desc')
         ->limit(3);

$this->db->join('comments', 'blog_entry_id = blog.id')
         ->group_by('blog_entry_id')
         ->count_all_results('comments'); 

我该怎么办?我做错了什么?

推荐答案

:)

$this->db->select('blog.*, COUNT(comments.id) as num_comments')
         ->from('blog')
         ->order_by('blog.id', 'desc')
         ->limit(3);

$this->db->join('comments', 'blog_entry_id = blog.id')
         ->group_by('blog_entry_id');

这篇关于CodeIgniter:计算连接表的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆