【问题标题】:Refactor string in MySQL field重构 MySQL 字段中的字符串
【发布时间】:2019-10-14 15:01:53
【问题描述】:

我搜索并找不到解决此问题的方法。我要更新下表:

+--------------------+
| description        |
+--------------------+
| Interna_172_16_1   |
| Interna_172_16_2   |
| Interna_172_16_3   |
| Interna_172_16_4   |
| Interna_172_16_5   |
+--------------------+

使用相同的字符串,但从最后一个数字 f.e. 中减去一个:

+--------------------+
| description        |
+--------------------+
| Interna_172_16_0   |
| Interna_172_16_1   |
| Interna_172_16_2   |
| Interna_172_16_3   |
| Interna_172_16_4   |
+--------------------+

我怎样才能做到这一点?抱歉英语不好,谢谢!!

【问题讨论】:

    标签: mysql select sql-update


    【解决方案1】:

    您可以这样做。 表名需要修改

    UPDATE Table1
    SET description = CONCAT(SUBSTRING_INDEX(`description`, '_', 3)
                       ,'_',SUBSTRING_INDEX(`description`, '_', -1) -1);
    

    【讨论】:

      【解决方案2】:

      你可以使用:

      update yourtable
      set description = 
        concat(left(description, length(description)-1), right(description,1)-1)
      where right(description,1) regexp '[1-9]+'
      

      【讨论】:

        【解决方案3】:

        如果需要选择语句:

        select concat(
          left(description, length(description) - length(substring_index(description, '_', -1))),
          substring_index(description, '_', -1) - 1
        ) description                                                         
        from tablename
        

        请参阅demo。
        如果要更新表格:

        update tablename
        set description = concat(
          left(description, length(description) - length(substring_index(description, '_', -1))),
          substring_index(description, '_', -1) - 1
        );
        

        见demo。

        结果:

        | description      |
        | ---------------- |
        | Interna_172_16_0 |
        | Interna_172_16_1 |
        | Interna_172_16_2 |
        | Interna_172_16_3 |
        | Interna_172_16_4 |
        

        此代码假定所有描述都以数字字符串结尾。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-02-23
          • 2013-10-16
          • 2011-10-13
          • 2014-11-25
          • 1970-01-01
          • 2019-12-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多