Mysql 用于确定相关标记的查询

Mysql 用于确定相关标记的查询,mysql,sql,Mysql,Sql,我希望在构造一种有效的方法来挑选相关标签方面能得到一些帮助 粗略数据库: CREATE TABLE blog ( blog_id INT, ... ); CREATE TABLE tag ( blog_id INT tag VARCHAR(20), ); CREATE TABLE tag_count ( tag VARCHAR(20), times INT ); 表“tag”如下所示: 1, 'cat' 1, 'cheeseburger' 2

我希望在构造一种有效的方法来挑选相关标签方面能得到一些帮助

粗略数据库:

CREATE TABLE blog (
    blog_id INT,
    ...
);

CREATE TABLE tag (
    blog_id INT
    tag VARCHAR(20),
);

CREATE TABLE tag_count (
    tag VARCHAR(20),
    times INT
);
表“tag”如下所示:

1, 'cat'
1, 'cheeseburger'
2, 'dog'
2, 'cheeseburger'
2, 'ham'
'cat', 1
'cheeseburger', 2
'dog', 1
'ham', 1
表“tag_count”如下所示:

1, 'cat'
1, 'cheeseburger'
2, 'dog'
2, 'cheeseburger'
2, 'ham'
'cat', 1
'cheeseburger', 2
'dog', 1
'ham', 1
我正在尝试查找条目的相关标记。例如,如果你在看blog 2,相关的标签是“cat”,因为两个blog条目都有“cheeseburger”标签。如果你看博客1,相关的标签是“dog”和“ham”,因为这两个条目都有“cheeseburger”标签

因此,该方法应该根据blog_id查找相关标记,并忽略共享标记,即“cheeseburger”。确定这些相关标签的最有效方法是什么?我包括tag_count,因为理想情况下,我希望按times DESC排序,以便找到最相关的标记


非常感谢

您似乎想要的是其他博客上与某个给定博客共享标签的附加标签

因此,这意味着一些连接和排除:

select t.tag, count(*)
from (select t2.blog_id as other_blog_id
      from tags t join
           tags t2
           on t.tag = t2.tag and
            t.blog_id <> t2.blog_id 
      where t.blog_id = 2
     ) o join
     tags t
     on o.other_blog_id = t.blog_id
where not exists (select 1
                  from tags tt
                  where tt.blog_id = 2 and tt.tag_id = t.tag_id
                 )
group by t.tag;

第一个子查询获取相关的blog id。然后,外部查询将其连接回标记,而notexists将排除blog 2中已有的标记。

您似乎想要的是其他blog上与某个给定blog共享标记的附加标记

因此,这意味着一些连接和排除:

select t.tag, count(*)
from (select t2.blog_id as other_blog_id
      from tags t join
           tags t2
           on t.tag = t2.tag and
            t.blog_id <> t2.blog_id 
      where t.blog_id = 2
     ) o join
     tags t
     on o.other_blog_id = t.blog_id
where not exists (select 1
                  from tags tt
                  where tt.blog_id = 2 and tt.tag_id = t.tag_id
                 )
group by t.tag;
第一个子查询获取相关的blog id。然后外部查询将其连接回标记,not exists将排除blog 2中已有的标记。

我认为表标记应称为BlogTags,因为它本质上是一个连接表。我认为表标记应称为BlogTags,因为它本质上是一个连接表。