【问题标题】:How to retrieve samples from the database?如何从数据库中检索样本?
【发布时间】:2013-08-19 19:39:39
【问题描述】:

假设我有许多标记实体(例如带有标记的博客文章)要存储在 SQL 数据库中。例如:

post1:工作 post2:工作、编程、java、工作 post3:工作、编程、sql post4:假期,照片 post5:假期 帖子6:照片

假设我也有一个标签列表

工作,假期

现在我想获得一个大小为 2 的帖子 sample,即两个带有列表中标签的帖子。例如

示例 1:post1 和 post2 示例 2:post1 和 post4 示例 3:post2 和 post5

此外,我希望 sample 包含列表中的所有标签。请注意,sample1 不满足此要求,因为示例实体的标签集不包含列表中的标签 vacation

我还希望所有标签的出现都相同。让我们考虑 2 个大小为 4 的样本。

示例 1:post1、post2、post3、post6 示例 2:post1、post3、post4、post5

请注意,sample1 不满足此要求,因为标签 work 在其中出现了 3 次,而 vacation 仅出现了一次。

我的问题是:如何设计一个关系数据库和 SQL 查询来检索给定大小的样本?

【问题讨论】:

    标签: sql database database-design rdbms


    【解决方案1】:

    如果您想获取所有带有逗号分隔列表中标签的帖子:

    select postid
    from post_tags
    where find_in_set(tagid, @LIST) > 0
    group by postid
    having count(distinct tagid) = 1+length(@LIST) - length(replace(',', @LIST, ''));
    

    如果您只想要其中的“样本”:

    select postid
    from (select postid
          from post_tags
          where find_in_set(tagid, @LIST) > 0
          group by postid
          having count(distinct tagid) = 1+length(@LIST) - length(replace(',', @LIST, ''))
         ) t
    order by rand()
    limit 5
    

    【讨论】:

    • 谢谢!你能解释一下having count(distinct tagid) = 1+length(@LIST) - length(replace(',', @LIST, ''))这件事吗?
    • @迈克尔。 . .那就是计算字符串中元素的数量。它是数字逗号加一。
    猜你喜欢
    • 2021-10-26
    • 2013-10-31
    • 2016-11-27
    • 2016-03-17
    • 2015-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多