【问题标题】:Tag Search System SQL标签搜索系统 SQL
【发布时间】:2021-06-21 20:59:13
【问题描述】:

我正在尝试建立一个系统,您可以在其中根据标签搜索帖子(使用 SQL 数据库)。

示例架构:

职位:ID、姓名

标签:id, name, post_id (foreign_key)

示例对象:

Posts:

{
    "id": 1,
    "name": "Post1"
}

{
    "id": 2,
    "name": "Post2"
}

Tags:

{
    "id": 1,
    "name": "Tag1",
    "post_id": 1
}

{
    "id": 2,
    "name": "Tag2",
    "post_id": 1
}

{
    "id": 3,
    "name": "Tag1",
    "post_id": 2
}

例如,我用 Tag1 和 Tag2 搜索

我想取回一个相关的列表(匹配多少标签)。

例子:

{
    "post_id": 1,
    "tag_count": 2
}

{
    "post_id": 2,
    "tag_count": 1
}

Id 开始于:

select * from recipes_tag where name in ("tag1", "tag2")

但是我找不到通过 post_id 来计算每个帖子在搜索中的标签数量的方法。

【问题讨论】:

    标签: sql database sqlite


    【解决方案1】:

    SQL 使用' 引用字符串。

    那么你可以只使用聚合来计算标签...

    SELECT
      post_id,
      COUNT(DISTINCT name)  AS count_of_tags
    FROM
      recipes_tag
    WHERE
     name IN ('tag1', 'tag2')
    GROUP BY
      post_id
    

    如果要确保至少有一定数量的匹配,请将其添加到末尾...

    HAVING
      COUNT(DISTINCT name) = 2
    

    【讨论】:

      猜你喜欢
      • 2011-01-04
      • 2011-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多