我昨天问了这个问题:
MySQL如何组合这些表?
我想通过标签搜索博客文章,我该怎么做?
同样,我的表格是:
blog_posts
int id (auto increment)
varchar(255) title
text content
blog_tags
int id (auto increment)
varchar(63) name
blog_posttags
int id (auto increment)
int post_id
int tag_id
我目前有以下查询,用于通过它的标签搜索博客文章,但我也想要它的标签(就像我之前的问题一样)。
SELECT a.*
FROM blog_posts a,
blog_tags b,
blog_posttags c
WHERE b.id = c.tag_id
AND c.post_id = a.id
AND b.name = "searchTag"
GROUP BY a.id
但这显然不会在博客信息中返回任何标签。
这可以在一个查询中完成吗?因为可能有不止一篇博客文章带有这个标签,我不想为每篇博客文章运行查询来找到它们的标签。
您只需将另一个查询与此查询组合即可。试试这个:
SELECT a.id
,a.title
,a.content
,(SELECT GROUP_CONCAT(b.name)
FROM blog_tags b
JOIN blog_posttags c
ON b.id = c.tag_id
WHERE c.post_id = a.id
) AS tags
FROM blog_posts a
INNER JOIN blog_posttags c ON c.post_id = a.id
INNER JOIN blog_tags b ON b.id = c.tag_id
WHERE b.name = "work"
GROUP BY a.id
sqlfiddle演示