【发布时间】:2012-10-16 16:11:35
【问题描述】:
仔细检查,如果我删除评论表连接,问题就解决了,但显然这不是理想的帮助!
我正在尝试使用 Codeigniter 写博客。目前我正在显示我想要显示的所有信息,但由于某种原因,在查看博客时,我有重复的类别内容。我的数据库中只有 3 个测试类别,但我的测试帖子中有 1 个选择了所有 3 个,显示了 6 个,而另一个只显示了一个类别两次。
比这更奇怪的是,第一篇博文还算错了 cmets 的数量。当数据库中只有 4 个并且只有两个与该帖子相关时,它显示 6,但最奇怪的是第二个帖子显示了正确的 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->join('posts_categories', 'posts_categories.blog_entry_id = posts.id', 'left outer', 'left outer');
$this->db->join('categories', 'posts_categories.blog_category_id = categories.category_id', 'left outer');
$this->db->join('comments', 'comments.post_id = posts.id', 'left outer' );
$query = $this->db->get('posts', $config['per_page'], $this->uri->segment(3));
生成的标准查询是这样的:
SELECT DISTINCT `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
FROM (`posts`)
LEFT OUTER JOIN `posts_categories` ON `posts_categories`.`blog_entry_id` = `posts`.`id`
LEFT JOIN `categories` ON `posts_categories`.`blog_category_id` = `categories`.`category_id`
LEFT JOIN `comments` ON `comments`.`post_id` = `posts`.`id`
GROUP BY `posts`.`id` LIMIT 1
可以找到数据库转储here
任何帮助将不胜感激,这让我发疯了!
干杯。
【问题讨论】:
-
您是否对您的数据库手动运行此查询?
-
正如Brendan所说,尝试直接在mysql中运行生成的查询,看看结果,这可以帮助你推断错误假设你知道sql(你可以通过$this-得到生成的查询>db->last_query())。考虑删除计数,以便您知道它正在计数哪些字段。这很可能是一个 sql 错误。还可以考虑使用“$this->db->distinct();”以避免重复的结果。
-
直接在我的数据库上运行它并且得到相同的错误,所以很明显我的查询有问题。将不得不尝试重新考虑它。尽管@Brendan @death_relic0 和想法将不胜感激!
-
这是有问题的查询 SELECT DISTINCT
posts.id,posts.title,posts.slug,posts.posts, @98 @.author,posts.date,posts.time,posts.tags,posts.status, GROUP_CONCAT(categories.name SEPARATOR) , count(cmets.id) as total_cmets FROM (posts) 左外连接posts_categoriesONposts_categories.blog_entry_id=posts.id左连接categories@98765434@posts_categories. =categories.category_idLEFT JOINcommentsONcomments.post_id=posts.idGROUP BYposts.idLIMIT 1 -
您可能需要提供一个 sql 转储来获得帮助,因为它非常具体。
标签: mysql codeigniter join left-join duplicate-data