连接表和循环

时间:2013-01-26 14:14:20

标签: mysql codeigniter

我已经加入了这样的帖子和标签表:

$this->db->select('*');
$this->db->from('posts');
$this->db->join('posts_tags', 'posts.post_id = posts_tags.post_id', 'left');
$this->db->join('tags', 'posts_tags.tag_id = tags.tag_id', 'left');

如何遍历每个帖子,并显示各自标签的列表。 例如:

post1: tag1, tag2
post2, tag1, tag3

目前,我可以显示标签,但它会为第1个帖子和第2个返回两行。现在的输出是:

post1: tag1
post1: tag2
post2: tag1
post2: tag3

如何在帖子中返回一行,其中包含所有相关标签?

1 个答案:

答案 0 :(得分:1)

使用group concat和group results

$this->db->select('posts.*');
$this->db->select('GROUP_CONCAT(posts_tags.tag_title) as TagTitles');
$this->db->from('posts');
$this->db->join('posts_tags', 'posts.post_id = posts_tags.post_id', 'left');
$this->db->join('tags', 'posts_tags.tag_id = tags.tag_id', 'left');
$this->db->group_by('posts.id');
$this->db->get();