【问题标题】:SQL to find articles with ALL of a set of tagsSQL 查找具有所有一组标签的文章
【发布时间】:2009-09-09 23:49:26
【问题描述】:

查找带有任意一组标签的文章是一个相对简单的连接,并且已经讨论过:Best DB (MySQL) structure: Articles which contain favored tags

但是,如果我正在搜索,并且想要查找带有所有标签集的文章怎么办?

为具体起见,假设以下表格:

CREATE TABLE `articles` (
   `id` INT NOT NULL
);

CREATE TABLE `applied_tags` (
   `tag_id` INT NOT NULL,
   `article_id` INT NOT NULL
);

CREATE TABLE `search_tags` (
   `search_id` INT NOT NULL,
   `tag_id` TAG NOT NULL
);

我想出了这个,我认为这可能可行,但它庞大、丑陋且有点不清楚,所以我认为一定有更好的方法:

Select articles.id from articles
where
 ( select count(*) from applied_tags
   where applied_tags.article_id == articles.id
     and applied_tags.tag_id in (select search_tags.tag_id from search_tags where search_tags.search_id == <input>) 
     ==
 (select count(*) from search_tags where search_tags.search_id == <input>)

(本质上,如果相关标签的数量是预期值,则计数。)

【问题讨论】:

    标签: sql


    【解决方案1】:
    select article_id
    from  applied_tags 
    where tag_id in (<input tag set here>)
    group by article_id
    having count(*) = <count of input tags>
    

    应该这样做。我不会发誓这是最有效的方法,但它会做你想做的事,假设 tag_id + article_id 是应用标签上的主键。如果不是(即,您可以有重复的标签),所有的赌注都将被取消。

    【讨论】:

    • 谢谢,这样更优雅。我想我也可以通过“从(从应用的标签中选择文章ID,其中标签ID == )”来加快速度。是的,我实际上对 (tag_id, article_id) 和 (article_id, tag_id) 都有唯一索引。
    • 如果我有一个多对多表 Actors_Roles 和另一个包含角色列表的表,并且想要查找所有角色都在角色中找到的演员,那么上面的这些表如何对应于我的?问题是否与开始类似?
    • 请参阅stackoverflow.com/questions/21393019/… 了解另一种解决问题的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-04
    • 2016-11-05
    • 1970-01-01
    • 1970-01-01
    • 2012-01-27
    相关资源
    最近更新 更多