搜索标签id相似的记录


Search for records with similar tag id

我有一个标签表,看起来像这样:

id  |  product_id | tag_id
---------------------------
1   |           1 |     10
2   |           1 |     12
3   |           2 |     10
4   |           3 |     11

我正在创建一个搜索页面,将标签作为用户(1个或更多)的输入,并搜索数据库中存在这些标签的记录。

例如:
  • 如果用户输入'10',那么使用上面的表,结果将是product_id 1 &2 .
编辑:

  • 有2个用户输入

    1. 包含标签->搜索具有这些标签的产品

    2. 排除标签->搜索没有这些标签的产品

所以搜索查询必须首先忽略排除标签,然后搜索带有'包含标签'的产品。

编辑2:

用户可以输入1个或多个标签。


你知道怎么做吗?

运行以下SQL查询:

$includedTags = join(',',$incTagsIdArr);
$excludedTags = join(',',$excTagsIdArr);
$sql = "SELECT product_id FROM $tagTable WHERE tag_id IN ($includedTags) AND tag_id NOT IN ($excludedTags)"

地点:

  • $incTagsIdArr是用户
  • 的请求标签id数组。
  • $excTagsIdArr是用户
  • 排除的标签id数组。
  • $tagTable是你的"标签"表名

下面是一个使用聚合和having的相当简单的方法:

select tt.product_id
from tagtable tt
group by tt.product_id
having sum(tt.tag_id in ($excludedtags)) = 0 and
       sum(tt.tag_id in ($includedtags)) = #NumberIncludedtags;

您需要为第二个条件输入所包含的标记的数量。此外,这假定标签表没有重复的行(如果有,可以通过使用count(distinct)轻松修复,但这会使查询变得混乱)。