就这样,我没有特别熟练这一点,这实际上是我第一次连接查询,所以要温柔。我会尽可能详细地提供尽可能多的细节,因为它可能会像煎锅一样击中你的大部分脸,但它正在做我的坚果!添加另一个数据库连接到我的查询造成一些行不被看到
我正在尝试在codeigniter中编写博客的查询问题。我建立了一个包含2个连接的查询,并使用三个表:分类,分类和posts_categories现在我试图加入我的评论表,做一个计数。
这是在我的模型代码,显示无论是一般职位我已经决定了:
$this->db->select('posts.id,
posts.title,
posts.slug,
posts.content,
posts.author,
posts.date,
posts.time,
posts.tags,
posts.status,
GROUP_CONCAT(categories.name SEPARATOR \'-\') AS categories
');
$this->db->group_by(array('posts.id'));
$this->db->from('posts');
$this->db->join('posts_categories', 'posts_categories.blog_entry_id = posts.id');
$this->db->join('categories', 'posts_categories.blog_category_id = categories.category_id');
$query = $this->db->get();
return $query->result_array();
这就是结果:
(
[0] => Array
(
[id] => 1
[title] => My first blog post!
[slug] => my-first-blog-post
[content] => This is my first blog post. Don't worry, it's just a test, my real blog won't be this boring, hopefully!
[author] => Joni
[date] => 2012-01-23
[time] => 00:00:00
[tags] => Testing
[status] =>
[categories] => Testing-More Tests-Test
)
[1] => Array
(
[id] => 2
[title] => This is another test-post
[slug] => this-is-another-test-post
[content] => Well you guessed it. another boring test post, enjoy!
[author] => Joni
[date] => 2012-01-23
[time] => 00:00:00
[tags] => Sexy
[status] =>
[categories] => Test
)
)
现在,当我修改查询以实现第三次加入,如下所示:
$this->db->select('posts.id,
posts.title,
posts.slug,
posts.content,
posts.author,
posts.date,
posts.time,
posts.tags,
posts.status,
GROUP_CONCAT(categories.name SEPARATOR \'-\') AS categories,
count(comments.id) as total_comments
');
$this->db->group_by(array('posts.id'));
$this->db->from('posts');
$this->db->join('posts_categories', 'posts_categories.blog_entry_id = posts.id');
$this->db->join('categories', 'posts_categories.blog_category_id = categories.category_id');
$this->db->join('comments', 'comments.post_id = posts.id');
$query = $this->db->get();
return $query->result_array();
我结束了这个
(
[0] => Array
(
[id] => 1
[title] => My first blog post!
[slug] => my-first-blog-post
[content] => This is my first blog post. Don't worry, it's just a test, my real blog won't be this boring, hopefully!
[author] => Joni
[date] => 2012-01-23
[time] => 00:00:00
[tags] => Testing
[status] =>
[categories] => Testing-More Tests-Test
[total_comments] => 3
)
)
如果你做了这一步,对不起这是这么长时间了,只是想提前说声谢谢!
欢呼乔尼
是什么问题?哪一行看不到? – safarov 2012-03-29 21:29:27
如果您的第二篇文章没有评论,则不会显示。这是你最后结果中发生的事情。 – OneSneakyMofo 2012-03-29 21:30:26