【问题标题】:SQL query find rows that share the same tagsSQL 查询查找共享相同标签的行
【发布时间】:2020-12-27 05:22:40
【问题描述】:

让我们看看是否有人可以帮助我... 在产品页面上,我必须显示相关产品。这些产品是相关的,取决于它们的标签。例如我的产品(ID 23)有以下标签:烹饪、面条、健康。

我要做的是一个 SQL 查询,它搜索带有“烹饪、面条、健康”标签但单独的产品

首先搜索标签中包含“烹饪”的所有产品,然后查找其他包含“面条”的产品,最后搜索“健康”。

显示的产品必须按顺序显示:首先显示标签列中包含“烹饪”的所有产品,然后显示“面条”,最后显示“健康”。重要的是,产品不必重复。

这是我希望得到的顺序:ID: 25, 25, 40, 43, 46

这是数据库

ID Tags Name
23 cooking, noodles, healthy Noodles Hot white pepper
25 cooking, noodles, healthy Soap of noodles
35 cooking, noodles, healthy Noodles with carrots
40 food, noodles, ketchup New Noodles with ketchup
43 apple, cook, healthy Apple with sugar
46 banana, cook, healthy Banana with sugar

感谢您的帮助!

【问题讨论】:

  • 在全文搜索中使用排名
  • 你能举个例子吗?真相不知道该怎么做。感谢您的回答
  • 您使用的是哪个 dbms?
  • 您应该修复您的数据库模型,以便您在单个列中存储多个值。

标签: sql csv tags


【解决方案1】:

您存储数据的方式使事情变得不必要地次优。您不应该将多个字符串存储在单个列中;相反,应该有另一个表来存储产品和标签之间的关系,每个元组应该在单独的行中。

对于您当前的设计,您可以:

select t.*
from mytable t
where 
    ',' || tags || ',' like '%,cooking,%'
    or ',' || tags || ',' like '%,noodles,%'
    or ',' || tags || ',' like '%,healthy,%'
order by 
    case
        when ',' || tags || ',' like '%,cooking,%' then 1
        when ',' || tags || ',' like '%,noddles,%' then 2
        else 3
    end,
    id

这使用标准字符串连接运算符||:您可能需要将其调整为您的实际数据库。

某些数据库具有搜索 CSV 列表的内置功能。例如,如果您正在运行 MySQL:

select t.*
from mytable t
where 
    find_in_set('cooking', tags)
    or find_in_set('noodles', tags)
    or find_in_set('healthy', tags)
order by 
    case
        when find_in_set('cooking', tags) then 1
        when find_in_set('noodles', tags) then 2
        else 3
    end,
    id

【讨论】:

  • 感谢您的推荐和查询,它运行完美。只有我有一个问题。我需要显示所有这些记录,例如 ID 为 25 的记录除外。我应该在查询中添加什么?
  • @BraiKaler:使用where 子句。 where id <> 25 and (find_in_set() or ...)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-18
  • 2014-09-19
  • 2016-05-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多