我对 SQL 查询的经验很少,但我的项目有这个要求,用于搜索和提供描述的自动建议。
Id Description
1 Processing Peater order
2 Dent in front panel
3 New item purchased
如果用户在文本框中输入“P ”,则
期望的结果
Processing
Peater
panel
purchased
<小时/>
注意:结果集中的每个值都是唯一的。 抱歉我的英语不是很好。
最佳答案
这在数据库中是一件很好的事情。问题是你的数据结构错误。当您将数据加载到表中时,您需要创建一个词典。词典可能只是单词数。或者,它基本上可以是一个倒排索引,其中的列为:
- 单词
- 身份证
- 职位
这为您提供了项目所需的数据结构。
为了创建这个数据结构,我基本上会一遍又一遍地运行以下查询来填充词典:
insert into lexicon(word, id, pos)
select substring_index(substring_index(description, ' ', pos), ' ', -1), id, pos
from t cross join
(select 1 as pos) const
where length(description) - length(replace(description, ' ', '')) >= pos;
每次增加子查询中 pos
的值。
编辑:
如果您知道描述中的最大字数,则无需新表格即可完成此操作。我不会推荐它。但这样的事情会起作用:
select distinct substring_index(substring_index(description, ' ', pos), ' ', -1) as word
from t cross join
(select 1 as pos union all
select 2 union all
select 3 union all
select 4 union all
select 5 union all
select 6 union all
select 7 union all
select 8 union all
select 9 union all
select 10 union all
) const
where length(description) - length(replace(description, ' ', '')) >= pos
having word like 'p%'
关于mysql - 按空间拆分列值并在新行中获取每个拆分值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18025251/