gpt4 book ai didi

mysql - 按找到的选项数量排序

转载 作者:行者123 更新时间:2023-11-29 14:16:56 27 4
gpt4 key购买 nike

我正在实现基于标签的搜索,用户可以插入多个标签来搜索特定实体。一个实体可以有任意多个标签。但不必将用户搜索的所有标签都列在结果中。

例如,当用户输入三个标签,例如“鞋子”、“皮革”、“正式”时,具有这些标签中的一个或多个标签的每个实体都可以在列表中。

我正在使用 union 返回具有这些关键字中的任何一个的实体的完整列表,但问题是我希望它们根据类别中找到的标签数量进行排序。

例如,具有所有三个标签“鞋子”、“皮革”、“正式”的实体应位于仅具有其中一两个标签的实体之上。是否有任何 sql 功能可以执行此类搜索?

[编辑]

我的表格布局是:

实体表

  • 实体名称
  • Entity_id(自动包含主键)

标签表

  • 标签
  • Entity_id

我无法实现我的目标。现在使用此查询:

select entity.entity_name from entity.entity_id join tags on tags.entity_id=entity.entity_id where tags.tag="first tag"
union
select entity.entity_name from entity.entity_id join tags on tags.entity_id=entity.entity_id where tags.tag="second tag"
union
select entity.entity_name from entity.entity_id join tags on tags.entity_id=entity.entity_id where tags.tag="third tag"

正如我所说,这并不能解决我的目的。

最佳答案

这应该适合你:

 select entity_name, count(*) count
from (
select e.entity_name, t.tag
from tag t
join entity e on (t.entity_id = e.entity_id)
where t.tag in ('tag', 'tag', 'tag')
)x
group by entity_name
order by count desc

它按实体对匹配的标签进行计数,然后将匹配度最高的标签排在最前面。

另请注意, bool 样式全文匹配将提供类似的功能。

关于mysql - 按找到的选项数量排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12486353/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com