REPLACE查询不会替换所有提到的字符

时间:2014-03-31 10:16:05

标签: mysql replace special-characters caret

我想编写一个使用函数concat / replace的查询,将书的标题更改为分配给该书的jpg文件名。 在书名中我有一些特殊字符。

  1. 所有特殊字符都应更改为 -
  2. 应删除空格
  3. 如果彼此相邻有两个特殊字符(例如:,"在下面的示例中),它们会合并为一个字符 -
  4. 例如: 书名:M。Mitchell,"随风而去#34; 文件名是:m-mitchell-gonewiththewind.jpg

    查询:

    select *
    REPLACE (REPLACE (REPLACE (REPLACE (REPLACE 
    ' ', ''),  /*white space - ok */
    '„', '-'), /*quotation - ok */
    '”', '-'), /*quotation - ok */
    ' \' ', '-'), /* apostrophe - ok */
     ' " ', '-') /*here is the problem*/
    from ...
    

    问题:

    1. AD 1
      • "改变为"
      • \"也改变为"

    2. AD 3我应该将新查询添加到另一列吗?或者使用IF?

3 个答案:

答案 0 :(得分:2)

  

For ..图书名称:M. Mitchell,"Gone with the wind"文件名为:m-mitchell-gonewiththewind.jpg

您的查询未在示例中失败。您的示例中没有字符'„''”'和字符序列' " '。因此查询没有按预期结果。

更改查询如下:

select 
  t,
  replace(
    replace( 
      trim( 
        replace( 
          replace( 
            replace( 
              replace( 
                replace( t, '.', ' ' ), -- replaces all dots
                ',', ' ' ), -- replaces all commas
              '„', ' ' ), -- replaces all „s
            '”', ' ' ), -- replaces all ”s
          '"', ' ' )  -- replaces all "s
      ), -- removes trailing spaces
      ' ', '-' ), -- replaces all space chars
    '--', '-' ) -- replaces all repeated hyphen -s
  as title
from ( select 'M. Mitchell,"Gone with the wind"' t ) titles ;
SQL Fiddle

上的

演示

答案 1 :(得分:0)

感谢你的想法

如果我运行您的查询:

select 
  t,
  replace(
   replace(
    replace( 
      trim( 
        replace( 
          replace( 
            replace( 
              replace( 
                replace( t, '.', ' ' ), -- replaces all dots
                ',', ' ' ), -- replaces all commas
              '„', ' ' ), -- replaces all „s
            '”', ' ' ), -- replaces all ”s
          '"', ' ' )  -- replaces all "s
      ), -- removes trailing spaces
      ' ', '-' ), -- replaces all space chars
    '--', '-' ), -- replaces all repeated hyphen -s
    '&', '')
  as title
from ( select 'M. Mitchell,"Gone with the wind & fire'' "' t ) titles ;

结果:
  - 为&没问题   - 对于英寸标志''遗体'

如果我从数据库检查这个真实数据的查询,我仍然遇到问题&和'
  - & >改为&
  - '' >根本没有改变''

答案 2 :(得分:0)

好的,我找到了解决方案。
首先需要改变&进入空间然后使用修剪查询。

谢谢!