是否有任何方法将关联查询显示为行


Is there any way do display an associated query as row?

我有三个表,如下所示:

#Blog:
ID | Title
1    "My first blog"
2    "My second blog"
#Tags:
ID | Name
1   "Sport"
2   "Music
#tag_blog
Blog_id |   Tag_id
1           1
2           1
2           2

我想把它们作为显示在我的网页上

Blog_title  Tag_name
My first blog   Sport
My second blog  Sport, Music

在php文件中,我正在做一些类似的事情

if ($query->num_rows() > 0)
{
   foreach ($query->result() as $row)
   {
      echo $row->title;
      echo $row->tag;
   }
}

但当我使用联接时,它显示3行,其中一行一行地标记。想得到预期的结果吗?

Uou应使用聚合GROUP_CONCT函数-

SELECT b.Title AS Blog_title, GROUP_CONCAT(t.name) AS Tag_name FROM Blog b
  JOIN tag_blog tb
    ON tb.Blog_id = b.Blog_id
  JOIN Tags t
    ON t.Tag_id = tb.Tag_id
GROUP BY b.ID