【发布时间】:2012-04-13 14:17:45
【问题描述】:
对了,这个我不是特别熟练,这其实是我第一次join查询,所以要温柔。我将提供尽可能多的细节,因为它可能会像煎锅一样击中你们大多数人的脸,但它正在让我疯狂!
我在查询我尝试在 codeigniter 中编写的博客时遇到问题。我已经为帖子设置了一个包含 2 个连接的查询,它是使用三个表的类别:帖子、类别和 posts_categories 现在我也在尝试加入我的 cmets 表来进行计数。
这是我的模型中的代码,它显示了我编写的两个通用帖子:
$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
)
)
现在,当我修改查询以实现 cmets 的第三个连接时,如下所示:
$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
)
)
如果你已经做到了这一步,对不起,拖了这么久,只是想提前说声谢谢!
干杯乔尼
【问题讨论】:
-
有什么问题?哪一行没有看到?
-
如果您的第二个帖子没有评论,则不会显示。这就是您的底部结果中发生的情况。
标签: php mysql codeigniter join