0

我需要进行一个查询,以匹配tag_id在 table 中匹配的博客tags_blogs。还有另一个表包含我现阶段不关心的实际标签。

如何获取此表格内容:

reference_id    tag_id  blog_id
1               1       1   
2               2       1   
3               10      6   
4               11      6   
5               10      7   
6               11      7
7               11      8   

并返回这个 where (例如)blog_id = 6

blog_id  total_matches
7           2
8           1

换句话说,返回任何与提供的参数匹配的 tag_id 的博客 id,以及达到多少匹配的计数。

这是我到目前为止的代码(到目前为止我还很遥远):

SELECT blog_id FROM tags_blogs WHERE blog_id = 6
4

2 回答 2

2

您需要一个子查询来选择所有 6 个(或任何博客 id)标签,如果博客在该子查询中有一个标签 id,它将被选中,然后将相同的 blog_id 组合在一起并计算它们。

SELECT 
     a.blog_id,
     count(*) as total_matches
FROM 
     tags_blogs as a
WHERE 
     a.tag_id IN
     ( SELECT tag_id FROM tags_blogs WHERE b.blog_id=6 ) AND
     a.blog_id!=6 
GROUP BY a.blog_id

将返回类似的结果

blog_id   total_matches
7         2
8         2 
于 2013-07-01T18:07:20.790 回答
1

根据您的评论,这更像是您正在寻找的内容。请注意,此特定查询不一定是最佳的

select tb.blog_id, count(*) 
  as total_matches 
  from tags_blogs tb
  where tag_id in (select distinct tag_id from tags_blogs where blog_id = 6)
    and blog_id != 6
  group by blog_id

链接到 SQL 小提琴

您可能会发现这在某些情况下效率更高,或者更容易创建:

select tb.blog_id, count(*) 
  as total_matches 
  from tags_blogs tb
    join tags_blogs tb1 on tb1.tag_id = tb.tag_id and tb1.blog_id != tb.blog_id
    where tb1.blog_id = 6
  group by tb.blog_id;
于 2013-07-01T18:12:49.490 回答