[英]How to JOIN tables to SELECT articles with multiple tags?
I have a standard article, tags, and tag_map tables. 我有一个标准的文章,标签和tag_map表。 I
SELECT
authors by a single tag as 我通过一个标签
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
but how I can SELECT
articles having two or multiple tags? 但是如何
SELECT
具有两个或多个标签的文章?
Couple of simple ways. 几个简单的方法。
Join but where the tag is one of the ones required. 加入,但标记是必需标记之一。 Count the DISTINCT articles (as otherwise the count will be doubled), but check that the article has 2 tags using a HAVING clause.
对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
Or you could just do an extra join. 或者,您可以进行额外的加入。
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
You need use conditional Count
in your HAVING
clause. 您需要在
HAVING
子句中使用条件Count
。 Try this: 尝试这个:
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
use conditional count()
in your having
使用条件
count()
在having
if you can have duplicated tags you use 如果您可以使用重复的标签
HAVING COUNT(CASE WHEN c.tag ='tag1' THEN 1 END) >= 1
AND COUNT(CASE WHEN c.tag ='tag2' THEN 1 END) >= 1
if tags are unique you can simplify to 如果标签是唯一的,则可以简化为
HAVING COUNT(CASE WHEN c.tag IN ('tag1', 'tag2') THEN 1 END) = 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.