【问题标题】:Updating a column in MySQL using its previous value [duplicate]使用以前的值更新 MySQL 中的列 [重复]
【发布时间】:2018-02-20 13:43:02
【问题描述】:

我在 mysql 'url_map' 中有一个包含 2 列的表:id、url,其中填充了一些值。像这样的:

+----+-----------------------------------------+ | id | url | +----+-----------------------------------------+ | 1 | http://myserver.mywebsite.com/file1.txt | | 2 | http://myserver.mywebsite.com/file2.txt | +----+-----------------------------------------+

我的要求是使用之前的值将表中每一行的“url”更新为新值。

+----+---------------------------------------------+ | id | url | +----+---------------------------------------------+ | 1 | https://mynewserver.mywebsite.com/file1.txt | | 2 | https://mynewserver.mywebsite.com/file2.txt | +----+---------------------------------------------+

如果你看到变化,在每一行中,'url'的值已经从

  • http:// 到 https://
  • myserver 到 mynewserver

url 中的其他内容保持原样。

谁能帮我写这个查询?

【问题讨论】:

  • 替换函数可以作为起点

标签: mysql sql database sqlite


【解决方案1】:

你可以直接在更新语句中使用之前的值

UPDATE your_table t SET t.url = REPLACE(REPLACE(t.url, 'http://', 'https://'), 'myserver', 'mynewserver')

【讨论】:

    【解决方案2】:

    我会简单地做一个UPDATE 声明,例如:

    UPDATE url_map
       SET url = REPLACE(REPLACE(url, 'http', 'https'),'myserver ','mynewserver')
    

    或者如果你想在一个 REPLACE 中完成它(因为 http 和 myserver 基本上是一个字符串)

    UPDATE url_map
       SET url = REPLACE(url, 'http://myserver', 'https://mynewserver')
    

    【讨论】:

      【解决方案3】:

      嗯,正如你的例子所说,你可以使用替换方法

      Update url_map
      Set    url = replace(url, 'http://myserver', 'https://mynewserver');
      

      【讨论】:

        【解决方案4】:

        我还没有对此进行测试,但理论上应该可以:

        UPDATE `url_map` SET url = REPLACE(url, "http://myserver", "https://mynewserver")
        

        【讨论】:

        • 你的语法错误。
        • 我的错,无论出于何种原因,我仍然牢记“SELECT”语法。更新了。
        【解决方案5】:

        您必须创建一个过程。在程序中循环遍历行并进行更改。有关详细说明,请参阅https://dev.mysql.com/doc/refman/5.7/en/create-procedure.html

        【讨论】:

        • 在这种情况下你不需要程序,做一个简单的更新会容易得多。在其他情况下,该程序可能是一个很好的解决方案:)
        猜你喜欢
        • 1970-01-01
        • 2020-01-14
        • 1970-01-01
        • 2011-11-19
        • 2021-01-23
        • 2018-10-21
        • 2013-09-27
        • 2018-11-26
        相关资源
        最近更新 更多