【问题标题】:REPLACE query does not replace all of the mentioned charactersREPLACE 查询不会替换所有提到的字符
【发布时间】:2014-05-10 15:20:52
【问题描述】:

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

  1. 所有特殊字符都应改为-
  2. 应删除空格
  3. 如果相邻有两个特殊字符(例如:,在下面的示例中),它们会合并为一个字符 -

例如: 书名:M. Mitchell,《乱世佳人》 文件名是: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. 公元 1
    • " 变为"
    • \" 也变为 "

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

【问题讨论】:

    标签: mysql replace special-characters caret


    【解决方案1】:

    对于..书名: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

    【讨论】:

      【解决方案2】:

      谢谢你的想法

      如果我运行您的查询:

      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 ;
      

      结果:
      - 对于 & 没问题
      - 对于英寸符号 '' 仍然是 '

      如果我根据数据库中的真实数据检查此查询,我仍然对 & 和 '' 有问题
      - & > 改为 &
      - '' > 完全没有改变 ''

      【讨论】:

        【解决方案3】:

        好的,我找到了解决方案。
        首先需要将 & 变成空格,然后使用 trim 查询。

        谢谢!

        【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-22
        • 2012-09-25
        • 2016-04-19
        • 1970-01-01
        • 2021-05-02
        相关资源
        最近更新 更多