按空格拆分列值并将每个拆分值放入新行

时间:2013-08-02 20:01:26

标签: mysql sql

我对SQL查询的经验很少,但我对我的项目有这个要求,用于搜索和提供描述的自动建议。

Id            Description
1                 Processing Peater order
2                 Dent in front panel 
3                 New item purchased

如果用户在文本框中输入“P”,则

期望的结果

Processing 
Peater
panel
purchased 

注意:结果集中的每个值都是唯一的。 对不起,我的英语不是很好。

1 个答案:

答案 0 :(得分:0)

在数据库中这是一件好事。问题是您的数据结构错误。将数据加载到表中时,需要创建一个词典。词典可能只是一个单词的数量。或者,它基本上可以是倒置索引,其列为:

  • 编号
  • 位置

这为您提供了项目所需的数据结构。

要创建这个数据结构,我基本上会反复运行以下查询来填充词典:

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%'
相关问题