2010-09-24 68 views
7

我想知道如何通过匹配的标签数量来匹配具有匹配标签的商品。通过匹配的标签数量来匹配标签订购商品

比方说,你有三个MySQL表:

  • tags(tag_id, title)
  • articles(article_id, some_text)
  • articles_tags(tag_id, article_id)

现在让我们假设你有四篇文章,其中:

​​有标签“幽默“,”f unny“和”搞笑“。

article_id = 2标签“有趣”,“愚蠢”和“愚蠢”。

article_id = 3标签为“有趣”,“愚蠢”和“愚蠢”。

article_id = 4有标签“完全严重”。

您需要至少找到一个匹配标签,才能找到与article_id = 2相关的所有文章,并按照最佳匹配顺序返回结果。换句话说,article_id = 3应该是第一个,​​秒,article_id = 4应该不会出现。

这是可以在SQL查询或单独执行的东西,还是更适合像Sphinx这样的东西?如果前者,应该完成哪种查询,以及应该为最高性能结果创建什么类型的索引?如果后者,请扩大。

回答

10

尝试这样:

select article_id, count(tag_id) as common_tag_count 
from articles_tags 
group by tag_id 
where tag_id in (
    select tag_id from articles_tags where article_id = 2 
) and article_id != 2 
order by common_tag_count desc; 

语法可能需要MySQL的一个小调整。

或这一个,实际工作:;-)

SELECT at1.article_id, Count(at1.tag_id) AS common_tag_count 
FROM articles_tags AS at1 INNER JOIN articles_tags AS at2 ON at1.tag_id = at2.tag_id 
WHERE at2.article_id = 2 
GROUP BY at1.article_id 
HAVING at1.article_id != 2 
ORDER BY Count(at1.tag_id) DESC; 
+0

第二种语法非常棒,并且完全按照我需要的方式工作。非常感谢! – 2010-09-24 07:20:20

2

类似的东西:

SELECT a.* 
FROM articles AS a 
INNER JOIN articles_tags AS at ON a.id=at.article_id 
INNER JOIN tags AS t ON at.tag_id = t.id 
WHERE t.title = 'funny' OR t.title = 'goofy' OR t.title = 'silly' AND a.id != <article_id> 
GROUP BY a.id 
ORDER BY COUNT(a.id) DESC 

只需通常的指标,假设articles_tags有(article_id的,TAG_ID)PK,和index on tags.title