首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >返回直接出现在“感兴趣的单词”之前的单词列表

问返回直接出现在“感兴趣的单词”之前的单词列表
EN

Stack Overflow用户
提问于 2020-04-16 13:07:36
回答 2查看 47关注 0票数 1

实际上,我有一列长文本值,例如:

代码语言:javascript
复制
ID | text 
0  | Hi my name is Brian.
1  | I think Brian sucks.

我想写一个函数,返回紧跟在“感兴趣的单词”之前的单词列表。因此,如果我搜索"Brian",函数将返回"is“和"think”,因为这两个词都出现在"Brian“之前。到目前为止,我有以下代码,但它不起作用:

代码语言:javascript
复制
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
    from (
        select text from table as t, "Brian" as v
    ) as w;

有什么想法吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-04-16 13:20:42

您的查询中存在语法错误:

代码语言:javascript
复制
select text from table as t, "Brian" as v

应该是:

代码语言:javascript
复制
select text as t, "Brian" as v from table

一旦你解决了这个问题,你的输出是:

代码语言:javascript
复制
Hi my name is
I think

然后,您可以使用SUBSTRING_INDEX从这些字符串中提取最后一个单词:

代码语言:javascript
复制
select case when w.t regexp concat('[[:<:]]', w.v, '[[:>:]]') 
            then substring_index(substr(w.t, 1, locate(w.v, w.t)-2), ' ', -1)
            else null
       end as 'left_word',
       w.v as word
from (
  select text as t, "Brian" as v
  from `table`
) as w;

输出:

代码语言:javascript
复制
left_word   word
is          Brian
think       Brian

Demo on SQLFiddle

注对于MySQL > 8.0.4,您需要使用\\b而不是[[:<:]]和[[:>:]]作为单词边界,因此您的查询将变为

代码语言:javascript
复制
select case when w.t regexp concat('\\b', w.v, '\\b') 
            then substring_index(substr(w.t, 1, locate(w.v, w.t)-2), ' ', -1)
            else null
       end as 'left_word',
       w.v as word
from (
  select text as t, "Brian" as v
  from `table`
) as w;

Demo on dbfiddle

票数 3
EN

Stack Overflow用户

发布于 2020-04-16 14:31:52

您可以尝试执行以下查询:

代码语言:javascript
复制
select 
SUBSTRING_INDEX(SUBSTRING_INDEX(text, 'Brian', 1),' ',-2) 
from `table` 
where text LIKE '%Brian%'
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61243051

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档