使用多个连接计数
Counting with multiple joins
假设您有 3 个表:posts
、tags
、post_tag
。 posts
和tags
之间存在m:n关系,post_tag
用来连接它们。
您如何计算具有特定标签对的帖子数量?例如,计算同时标记有 "news" 和 "featured"?
的帖子数量
只需使用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')
这是关系划分的情况。有很多方法可以解决。
假设一个standard many-to-many implementation,这应该是最快和最简单的:
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');
计算 post 至少 给定的两个标签 。同一个 post.
可以有更多标签
我们在这个相关问题下汇集了一系列技术:
- How to filter SQL results in a has-many-through relation
假设您有 3 个表:posts
、tags
、post_tag
。 posts
和tags
之间存在m:n关系,post_tag
用来连接它们。
您如何计算具有特定标签对的帖子数量?例如,计算同时标记有 "news" 和 "featured"?
的帖子数量只需使用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')
这是关系划分的情况。有很多方法可以解决。
假设一个standard many-to-many implementation,这应该是最快和最简单的:
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');
计算 post 至少 给定的两个标签 。同一个 post.
可以有更多标签我们在这个相关问题下汇集了一系列技术:
- How to filter SQL results in a has-many-through relation