【问题标题】:MySql Trimming characters till a spaceMySql修剪字符直到空格
【发布时间】:2014-09-13 11:32:46
【问题描述】:

如何修剪(删除)从字符串右侧到第一个空格的所有字符?

这是我想要做的:

set @s:='May the Gods watch over your battles, my friend!';

select if(length(@s) < 10,@s,left(@s,10)) a;

#output from above: 'May the Go'

#desired output: 'May the'

为了避免像May the Go 这样的奇怪输出,我试图从右边修剪所有字符,直到第一个空格,所以输出是May the

如何在 sql 语句本身中做到这一点。我找不到可以执行此操作的内置函数?

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    这适用于 Microsoft SQL,如果您将 CHARINDEX 替换为 INSTR,它应该可以工作

    select substring(@s,1,charindex(' ',reverse(@s)))
    

    在下面添加了我的 SQL 小提琴版本,与 Microsoft SQL 中的工作方式有点不同

    http://sqlfiddle.com/#!2/d41d8/44718

    select @s,left(@s,10-locate(' ',reverse(@s)));
    

    数据库中的示例

    select theFld, 
    CASE    
         WHEN  length(theFld) <= 20 THEN theFld  
         ELSE
            left(theFld,20-locate(' ',reverse(left(theFld,20))))   
         END  as Abbr 
    FROM example;
    

    请参阅此 SQL 小提琴:http://sqlfiddle.com/#!2/beac7/6

    【讨论】:

    • 没什么。只返回一个空白。
    • 啊! Locate 是 MySql 的 charindex 等价物(或者至少在这里有效)
    • 您的解决方案使用“反向”,但仍以正确的方向输出数据。它是怎么做到的?
    • 所以,我是这样做的(使用我将使用的表):select if(length(string) &gt; 20,concat(left(string,20-locate(' ',reverse(string))),'&gt;&gt;&gt;'),string) a from string; 希望我没有做错任何事情。谢谢
    • 猜我说得太早了。将其添加到主应用程序,发现它不会工作。如何使用我的实际表及其列构建 sql?
    【解决方案2】:

    你可以试试这个方法:

    .....
    .....
    --define max length for the extracted text
    set @length:=10;
    set @result = 
              --check if either the last extracted character or... 
              --the character next to the last is a space (or both are spaces)  
              if(substring(@s, @length, 2) LIKE '% %',  
              --if true, extract using simple left()'
                left(@s,@length),
              --else, use the same simple left() operation then remove all characters.. 
              --starting from the right-most until the first space found
                replace(left(@s,@length), substring_index(left(@s, @length), ' ', -1), '')
              );
    

    [SQL Fiddle demo]

    供参考:MySQL String Last Index Of

    【讨论】:

    • 效果很好,但有点矫枉过正:-)
    • 你认为哪一部分是矫枉过正?我同意您可以使用substring()locate() 而不是replace(),但据我所知,if() 检查仍然是必要的。例如@length:=7
    • 我不认为这是矫枉过正,他添加了很多 cmets 来显示代码中发生了什么。我的答案中的 SQL-Server 示例较短,但没有 cmets。
    猜你喜欢
    • 1970-01-01
    • 2015-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    相关资源
    最近更新 更多