[英]Counting with multiple joins
Assuming you have 3 tables: posts
, tags
, post_tag
. 假设您有3个表:
posts
, tags
, post_tag
。 There's an m:n relationship between the posts
and tags
, post_tag
is used to connect them. posts
和tags
之间存在m:n关系, post_tag
用于连接它们。
How would you count the number of posts that have a particular pair of tags? 您如何计算具有特定标签对的帖子数? For instance, counting the number of posts that are tagged with both "news" and "featured"?
例如,计算同时被“新闻”和“精选”标记的帖子的数量?
Simply use EXISTS
for it 只需使用
EXISTS
select count(*)
from posts
where exists(select 1 from post_tag
join tag on post_tag.tid = tag.tid
where post_tag.pid = posts.pid and tag.name = 'news') and
exists(select 1 from post_tag
join tag on post_tag.tid = tag.tid
where post_tag.pid = posts.pid and tag.name = 'featured')
This is a case of relational division . 这是关系分裂的情况。 There are many ways to solve it.
有很多解决方法。
Assuming a standard many-to-many implementation , this should be among the fastest and simplest: 假设采用标准的多对多实现 ,那么这应该是最快,最简单的方法之一:
SELECT count(*)
FROM post_tag pt1
JOIN post_tag pt2 USING (post_id)
WHERE pt1.tag_id = (SELECT tag_id FROM tags WHERE tag = 'news')
AND pt2.tag_id = (SELECT tag_id FROM tags WHERE tag = 'featured');
That's counting posts with at least the two given tags. 这是在计算至少带有两个给定标签的帖子。 There can be more tags for the same post.
同一篇文章可以有更多标签。
We have assembled an arsenal of techniques under this related question: 在这个相关的问题下,我们已经组建了一个技术库:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.