【问题标题】:MySQL query to return all the text between the two words indicated (substring?)MySQL 查询返回指示的两个单词之间的所有文本(子字符串?)
【发布时间】:2016-06-09 16:59:27
【问题描述】:

我在表格的某一列中保存了一些长文本。

我想从中获取文本的一部分... 例如,'words' IMPORTANTSTART 和 IMPORTANTEND 之间的所有内容...

如果我不知道那部分的确切长度,我怎么能得到它? 我不能使用 SUBSTRING(),因为字符数总是不同的。

有没有办法做到这一点?我试图找到一些类似的功能可以让我这样做,但找不到任何东西......

A lot of words here IMPORTANTSTART some data IMPORTANTEND more words

Even more words IMPORTANTSTART very important data IMPORTANTEND words

也许有一种方法可以从查询输出中删除 IMPORTANTSTART 之前和 IMPORTANTEND 之后的所有内容,同时不更改数据库中的此文本?

【问题讨论】:

    标签: mysql sql substring


    【解决方案1】:

    试试SUBSTRING_INDEX:

    SET @s := 'A lot of words here IMPORTANTSTART some data IMPORTANTEND more words';
    
    SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(@s, 'IMPORTANTSTART', -1), 'IMPORTANTEND', 1)
    

    输出:

    some data 
    

    【讨论】:

    • 是否可以修改它以用于子查询给出的多行?
    • 结果是否可能是:IMPORTANTSTART some data IMPORTANTEND?
    • @inside83 是的,这是可能的
    • 如果你能写出来会非常有帮助
    • 感谢@GiorgosBetsos,它解决了我在图片网址中提取数字的请求,例如 text_12.jpg :sql SELECT substring_index(substring_index(url, '_', -1), '.', 1)
    【解决方案2】:

    我认为这可行。例如,我分别使用字符串 abccba 作为开始和结束分隔符。

    select @string := 'text abc important cba more text'
         , @start_delim := 'abc'
         , @end_delim := 'cba'
         , @start_pos := instr(@string, @start_delim) + length(@start_delim)
         , @end_pos := instr(@string, @end_delim)
         , mid(@string, @start_pos, length(@string) - @end_pos - 1)
    

    编辑

    您需要做的就是添加您的表格以将其用于您的所有数据。此外,您可以使用子查询来初始化相关变量和“紧凑”表达式,以便您只获得所需的内容:

    select articles
         , mid(
             articles, 
             instr(articles, @start_delim) + length(@start_delim),
             length(articles) - instr(articles, @end_delim) - 1
           ) as result
    from (select @start_delim := 'abc', @end_delim := 'cba') as init
       , myarchive
    

    如您所见,只需将 @string 替换为您要使用的列名即可。

    【讨论】:

    • 如何修改它以用于多行?我可以循环遍历表中的多行而不是直接在@string := 处插入行吗?只需插入一个子查询 - 例如 (SELECT articles FROM myarchive) - 而不是 'text abc important cba more text' 就会给我一个“子查询返回超过 1 行”错误。
    【解决方案3】:

    您可以使用INSTR 计算SUBSTRING 的开始/结束索引。

    【讨论】:

      猜你喜欢
      • 2014-05-28
      • 2021-04-02
      • 1970-01-01
      • 1970-01-01
      • 2020-07-22
      • 2015-04-10
      • 2013-12-12
      • 1970-01-01
      相关资源
      最近更新 更多