【问题标题】:Tags system - searching with 'some tags' AND without 'other tags'标签系统 - 使用“一些标签”和不使用“其他标签”进行搜索
【发布时间】:2014-01-14 19:29:46
【问题描述】:

我试图这样做:

两个输入:

1."用标签搜索问题:" 2.“无标签”

TABLE: questions (
-id,
-url,
 .
 .
 .
-other data
)

TABLE: tags (
-id,
-tag
)

TABLE: tags_and_questions (
-id,
-question_id,
-tag_id
)

SELECT `question_id` FROM `tags_and_questions` WHERE `tag_id` IN ($ok_tags_id) AND `tag_id` NOT IN ($no_tags_id)

tags_and_questions 表中的数据示例:

question_id   tag_id
   1            1
   1            2
   1            3

当$no_tags_id = 3时,获取tags_and_questions的结果是数组([0] => 1, [1] => 1)

这个表可以吗?

【问题讨论】:

    标签: php mysql search tags


    【解决方案1】:

    解决此问题的一种方法是使用带有having 子句的聚合:

    SELECT `question_id`
    FROM `tags_and_questions`
    GROUP BY question_id
    HAVING sum(`tag_id` IN ($ok_tags_id)) > 0 and
           sum(`tag_id` NOT IN ($no_tags_id)) = 0;
    

    这将返回包含一个或多个来自“ok”标签且没有“no”标签的问题。

    当然,这种结构假定您实际上是在将 SQL 创建为一个字符串来传递它。否则,“列表”将被视为单个值。

    编辑:

    如果查询没有返回任何行,那么我怀疑这是因为您的列表是作为单个字符串输入的。在 MySQL 中,你可以这样做:

    SELECT `question_id`
    FROM `tags_and_questions`
    GROUP BY question_id
    HAVING sum(find_in_set(`tag_id`, $ok_tags_id) > 0) > 0 and
           sum(find_in_set(`tag_id`, $no_tags_id) > 0) = 0;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-14
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      • 2019-05-23
      • 2021-05-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多