这是我的表格
注意 此表仅供参考
帖子
++++++++++++++++++++++++++++++++++++++++
+ id |title | desc | uid |status |
++++++++++++++++++++++++++++++++++++++++
+ 1 | a | aaaa | 1 | 1 |
++++++++++++++++++++++++++++++++++++++++
+ 2 | b | bbbb | 1 | 1 |
++++++++++++++++++++++++++++++++++++++++
+ 3 | c | cccc | 2 | 1 |
++++++++++++++++++++++++++++++++++++++++
猫
+++++++++++++++++++++++++++++++++
+ id | name |parent | status |
+++++++++++++++++++++++++++++++++
+ 1 | cat1 | 0 | 1 |
+++++++++++++++++++++++++++++++++
+ 2 | cat2 | 0 | 1 |
+++++++++++++++++++++++++++++++++
代码
+++++++++++++++++++++++++
+ id | name | title |
+++++++++++++++++++++++++
+ 1 | tag1 |ttitle |
+++++++++++++++++++++++++
+ 2 | tag2 |title2 |
+++++++++++++++++++++++++
Linked_data
作为一个2多关系船链接
链接名称 帖子ID cat_or_tag_id
+++++++++++++++++++++++++++++
+ name | r1 | r2|
+++++++++++++++++++++++++++++
+ cat | 1 | 1 |
+++++++++++++++++++++++++++++
+ cat | 1 | 2 |
+++++++++++++++++++++++++++++
+ tag | 1 | 2 |
+++++++++++++++++++++++++++++
我希望获得带有猫和标签的帖子
最好的方法是什么
我现在知道的唯一方法 得到帖子然后foreach post获取它的猫和标签
答案 0 :(得分:5)
SELECT Posts.*, GROUP_CONCAT(Cats.name) AS Cats, GROUP_CONCAT(Tags.name) AS Tags
FROM Posts
LEFT JOIN Linked_data ON Linked_data.r1 = Posts.id
LEFT JOIN Cats ON Linked_data.r2 = Cats.id AND Linked_data.name = 'cat'
LEFT JOIN Tags ON Linked_data.r2 = Tags.id AND Linked_data.name = 'tag'
GROUP BY Posts.id
在sqlfiddle上查看。
答案 1 :(得分:0)
我希望这会有所帮助
select p.title, c.name , t.name from posts p
inner join (select group_concat(c1.name), c1.id from cats c1 group by c1.id ) c on p.id = c.id
inner join (select group_concat(t1.name), t1.id from tags t1 group by t1.id ) t on p.id = t.id