MySQL - 查找围绕搜索关键字的单词

时间:2013-10-02 15:33:56

标签: mysql regex

假设我有一个随机文本,例如:

Lorem ipsum dolor sit amet consectetur adipiscing elit.

使用MySQL,我想搜索一个给定的关键字,并获得一个返回以及围绕我的关键字的直接词。

示例:

Select * from table where keyword like "%amet%"

返回整个文本。但我需要一个只返回以下文本的查询:

sit amet consectetur

所以,我搜索的这个词加上上一个和下一个词。

-

此外,如果我搜索关键字 elit ,则应返回(因为'elit'后面没有单词):

adipiscing elit

如果我搜索关键字 Lorem ,则应返回(因为'Lorem'之前没有任何字词):

Lorem ipsum

这可以以某种方式完成吗? 使用正则表达式或空格检测,使用MID或某种子串?

1 个答案:

答案 0 :(得分:1)

我有一个游戏,我可以用纯mysql给你半个解决方案。

你可以在使用它之后获得单词的任意一侧。只是不知道如何得到这个词而不是整个子串。希望它有用。

select case when (select w.t regexp concat('[[:<:]]', w.v)) = 1 
    then substr(w.t, 1, locate(w.v, w.t)-1) else null end as 'left_word',
       w.v as word,
       case when (select w.t regexp concat(w.v, '[[:>:]]')) = 1 
    then substr(w.t, locate(w.v, w.t)+length(w.v)) else null end as 'right_word'
    from (
        select "Lorem ipsum dolor sit amet consectetur adipiscing elit." as t, "amet" as v
    ) as w;

select case when (select w.t regexp concat('[[:<:]]', w.v)) = 1 
    then substr(w.t, 1, locate(w.v, w.t)-1) else null end as 'left_word',
       w.v as word,
       case when (select w.t regexp concat(w.v, '[[:>:]]')) = 1 
    then substr(w.t, locate(w.v, w.t)+length(w.v)) else null end as 'right_word'
    from (
        select "Lorem ipsum dolor sit amet consectetur adipiscing elit." as t, "elit." as v
    ) as w;
相关问题