1

这是我的桌子

注意 此表仅作为示例

帖子

++++++++++++++++++++++++++++++++++++++++
+   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 |
+++++++++++++++++++++++++

链接数据

链接为一艘 2 多关系船

链接名称 postid cat_or_tag_id

+++++++++++++++++++++++++++++
+ name    |  r1         | r2|
+++++++++++++++++++++++++++++
+ cat     |  1          | 1 |
+++++++++++++++++++++++++++++
+ cat     |  1          | 2 |
+++++++++++++++++++++++++++++
+ tag     |  1          | 2 |
+++++++++++++++++++++++++++++

我想获得带有猫和标签的帖子

最好的方法是什么

我现在知道的唯一方法 是获取帖子,然后 foreach 帖子获取它的猫和标签

4

2 回答 2

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上查看。

于 2012-08-05T11:15:49.660 回答
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
于 2012-08-05T11:16:29.373 回答