mysql使用GROUP CONCAT和JOIN选择多行

时间:2013-09-21 20:30:37

标签: mysql sql join group-concat

这是我一直在努力解决的问题。 我需要从特定博客ID中提取所有帖子。另外,我需要提取属于每个帖子的所有标签。

问题是当帖子没有标签时,查询不会返回它。如何为标签单元格获取空结果而不是不对该行进行重新定位?

我有以下表格

帖子:

ID  title
74  HELLO
75  HELLO2
76  HELLO3

tags_relation:

ID|post_id|tag_id
57  74       3
56  74       61
58  75       62
59  75       63

标记:

ID  tag
3   Love
61  Sometag
62  Sometag1
63  Sometag2
64  Sometag3
65  Sometag4

这是我的疑问:

SELECT post . * ,
   user.username,
   user.picture,
   GROUP_CONCAT(tag.tag SEPARATOR ',') AS tags
FROM `posts` AS post
INNER JOIN `users` AS USER ON USER.blog_id = post.blog_id
INNER JOIN `tags_relation` AS tags_relation
INNER JOIN `tags` AS tag ON tag.ID = tags_relation.tag_id
WHERE post.blog_id =1
  AND post.status = 'publish'
  AND post.ID = tags_relation.post_id
GROUP BY post.ID
ORDER BY post.timestamp DESC LIMIT 0,10;

1 个答案:

答案 0 :(得分:10)

试试这个:

SELECT p.* ,
   u.username,
   u.picture,
   GROUP_CONCAT(t.tag SEPARATOR ',') AS tags
FROM `posts` AS p
INNER JOIN `users` AS u ON u.blog_id = p.blog_id
LEFT JOIN `tags_relation` AS tr ON p.ID = tr.post_id
LEFT JOIN `tags` AS t ON t.ID = tr.tag_id
WHERE p.blog_id =1
  AND p.status = 'publish'
GROUP BY p.ID
ORDER BY p.timestamp DESC LIMIT 0,10;