【问题标题】:convert string to mysql query using regex使用正则表达式将字符串转换为 mysql 查询
【发布时间】:2014-07-07 16:09:31
【问题描述】:

我错误地更新了 MySQL 数据库中的一列,并将每一行设置为相同的值,如下所示:

ID  keyword                 Default_value   
1   header_HOME             EXCURSIONS
2   footer_APARTMENTS      EXCURSIONS
3   index_Excursions       EXCURSIONS
4   header_Sea_Excursions   EXCURSIONS
5   home_Desert_Safari      EXCURSIONS
6   header_Sight_Seeing     EXCURSIONS
7   apartment_Shore_excursions  EXCURSIONS
8   header_Plan_excursions  EXCURSIONS
9   header_Others           EXCURSIONS
10  header_Hotels           EXCURSIONS

变成那样

 ID  keyword                 Default_value   
    1   header_HOME             HOME
    2   footer_APARTMENTS      APARTMENTS
    3   index_Excursions       Excursions
    4   header_Sea_Excursions   Sea Excursions
    5   home_Desert_Safari      Desert Safari
    6   header_Sight_Seeing     Sight Seeing
    7   apartment_Shore_excursions  Shore_excursions
    8   header_Plan_excursions  Plan_excursions
    9   header_Others           Others
    10  header_Hotels           Hotels 

现在我需要更新Default_value 列以匹配此模式:

  1. 记下keyword 列中的单词。
  2. 去掉header_前缀。
  3. 将下划线_ 替换为空格
  4. 在末尾追加Excursions

结果将相当于为每一行运行这样的命令:

UPDATE `my_table` SET `Default_value` = 'Desert_Safari' WHERE `id` = 5

【问题讨论】:

  • 普通,没有什么“关键”的。只是字符串转换。好吧,我假设有人会为你做这项工作。
  • 你会用什么语言执行正则表达式?

标签: mysql replace substring


【解决方案1】:

我认为这会做你想要的:

update table t
    set default_value = concat(replace(substring(keyword, 8), '_', ' '), ' Excursions')

我认为使用基本字符串函数比使用正则表达式更容易。

【讨论】:

  • +1 我开始这样写和回答,然后意识到我错过了理解 OPs 规范。这个答案是正确的 IMO,所以我不会为竞争的答案而烦恼。
  • 您需要将“Excursions”连接到最后。
  • 关键字不仅是 home_ 它是变量我更新我的问题
  • @shmosel 。 . .我现在做的。我回答后问题变了。
  • @tito11 。 . .在回答后更改您的问题可能会使答案无效。这被认为是不礼貌的。
猜你喜欢
  • 2020-07-17
  • 2016-07-13
  • 2020-09-23
  • 2021-09-16
  • 2012-01-28
  • 2022-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多