更新语句中的 mysql case 与 REPLACE
我目前有这样的事情:
UPDATE table1 SET column1 = REPLACE(column1, 'abc', 'abc1') WHERE column1 LIKE '%abc%';
UPDATE table1 SET column1 = REPLACE(column1, 'def', 'def1') WHERE column1 LIKE '%def%';
我正在尝试将这些合并到一个更新语句中,并尝试执行以下操作:
UPDATE table1
SET column1 =
CASE
WHEN column1 LIKE '%abc%' THEN REPLACE(column1, 'abc', 'abc1')
WHEN column1 LIKE '%def%' THEN REPLACE(column1, 'def', 'def1')
ELSE column1
END;
这是执行此操作的正确方法吗?我对案例/时间不熟悉。谢谢!
I currently have something like this:
UPDATE table1 SET column1 = REPLACE(column1, 'abc', 'abc1') WHERE column1 LIKE '%abc%';
UPDATE table1 SET column1 = REPLACE(column1, 'def', 'def1') WHERE column1 LIKE '%def%';
I am trying to consolidate these into a single update statement and am trying the following:
UPDATE table1
SET column1 =
CASE
WHEN column1 LIKE '%abc%' THEN REPLACE(column1, 'abc', 'abc1')
WHEN column1 LIKE '%def%' THEN REPLACE(column1, 'def', 'def1')
ELSE column1
END;
Is this the correct way of doing this? I am new to case/when. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您使用的是
LIKE '%abc%'
,更新语句将需要全表扫描。在这种情况下,结合这两个语句将提高整体性能。但是,在您的建议中,每一行都会更新,并且大多数行都会更新而不更改(column1 值替换为column1 值)。您需要确保保留
WHERE
子句,以便仅更改真正需要更改的行。这种不必要的磁盘写入速度比检查行是否符合条件要慢。这样做:
Since you are using
LIKE '%abc%'
, the update statement will require a full table scan. In that case, combining the two statements will improve overall performance. However, in your suggestion, every single row is updated and most of them are updated without being changed (column1 value is replaced with column1 value).You want to make sure that you keep the
WHERE
clause so that only rows that really need change are changed. This unnecessary write to disk is slower than checking whether the row matches the criteria.Do this: