我有一个标准的文章,标签和tag_map表。我SELECT
作者用单个标签作为
SELECT author_id, COUNT(*) AS author_articles FROM articles a
JOIN tag_map b ON a.article_id=b.article_id
JOIN tags c ON b.tag_id=c.tag_id AND c.tag='tag1'
JOIN author_map d ON a.article_id=d.article_id
JOIN authors e ON d.author_id=e.author_id
GROUP BY e.author_id
但我如何SELECT
有两个或多个标签的文章?
答案 0 :(得分:2)
一些简单的方法。
加入,但标签是必需的标签之一。计算DISTINCT文章(否则计数将加倍),但使用HAVING子句检查文章是否有2个标签。
SELECT author_id,
COUNT(DISTINCT a.article_id) AS author_articles
FROM articles a
JOIN tag_map b ON a.article_id=b.article_id
JOIN tags c ON b.tag_id = c.tag_id AND c.tag IN ('tag1', 'tag2')
JOIN author_map d ON a.article_id=d.article_id
JOIN authors e ON d.author_id=e.author_id
GROUP BY e.author_id
HAVING COUNT(DISTINCT c.tag_id) = 2
或者你可以做一个额外的加入。
SELECT author_id,
COUNT(*) AS author_articles
FROM articles a
JOIN tag_map b ON a.article_id=b.article_id
JOIN tags c1 ON b.tag_id = c1.tag_id AND c1.tag = 'tag1'
JOIN tags c2 ON b.tag_id = c2.tag_id AND c2.tag = 'tag2'
JOIN author_map d ON a.article_id=d.article_id
JOIN authors e ON d.author_id=e.author_id
GROUP BY e.author_id
答案 1 :(得分:1)
您需要在Count
子句中使用条件HAVING
。
试试这个:
SELECT author_id, COUNT(*) AS author_articles FROM articles a
JOIN tag_map b ON a.article_id=b.article_id
JOIN tags c ON b.tag_id=c.tag_id
JOIN author_map d ON a.article_id=d.article_id
JOIN authors e ON d.author_id=e.author_id
GROUP BY e.author_id
HAVING COUNT(c.tag_id)>1
答案 2 :(得分:1)
在count()
having
如果您可以使用重复的标签
HAVING COUNT(CASE WHEN c.tag ='tag1' THEN 1 END) >= 1
AND COUNT(CASE WHEN c.tag ='tag2' THEN 1 END) >= 1
如果标签是唯一的,您可以简化为
HAVING COUNT(CASE WHEN c.tag IN ('tag1', 'tag2') THEN 1 END) = 2