这是我一直在努力解决的问题。
我需要从一个特殊的博客ID中提取所有的帖子。此外,我需要提取属于每个帖子的所有标签。
问题是当post没有标记时,查询就不会返回它。如何获取标记单元格的空结果而不是不重复行?
我有下列标签
帖子:
ID title
74 HELLO
75 HELLO2
76 HELLO3
标记关系:
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;
最佳答案
试试这个:
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;
关于mysql - MySQL使用GROUP CONCAT和JOIN选择多行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18937301/