mysql - 替换行内的部分值

标签 mysql sql wordpress

我在 WordPress 中有一个数据库表,它是从 Movable Type CMS 导入的,所以它并不完美。

  • 表:wp_posts
  • 列:post_content

post_content 内部是整个博客文章,在某些情况下,它们包含带有 URL 的内嵌图像,例如:

    ...post content...<img src="http://url.com/images/image1.jpg"/>...content
    ...post content...<img src="http://url.com/image2.jpg"/>...content

我试图让所有网址都指向http://url.com/images/

目前我将此作为我的 SQL 查询,仅当路径不是 url.com/images 时才有效,它会变成 url.com/images/images/:

UPDATE wp_posts
SET post_content = REPLACE(post_content,'url.com','url.com/images')
WHERE post_content LIKE '%url.com%';

有什么方法可以运行单个查询并将所有必要的行更新为相同的值吗?

最佳答案

最简单的方法是将现有网址转换为其他内容,运行原始查询,然后将它们全部恢复。

此查询会将 url.com/images 的所有实例替换为 [PLACEHOLDER]

UPDATE wp_posts
SET post_content = REPLACE(post_content,'url.com/images','[PLACEHOLDER]')
WHERE post_content LIKE '%url.com/images%';

现在运行原始查询以将 /images 附加到 url.com:

UPDATE wp_posts
SET post_content = REPLACE(post_content,'url.com','url.com/images')
WHERE post_content LIKE '%url.com%';

现在您可以将[PLACEHOLDER]向后移动:

UPDATE wp_posts
SET post_content = REPLACE(post_content,'[PLACEHOLDER]','url.com/images')
WHERE post_content LIKE '%[PLACEHOLDER]%';

全部集中在一起,方便复制和粘贴:

UPDATE wp_posts
SET post_content = REPLACE(post_content,'url.com/images','[PLACEHOLDER]')
WHERE post_content LIKE '%url.com/images%';
UPDATE wp_posts
SET post_content = REPLACE(post_content,'url.com','url.com/images')
WHERE post_content LIKE '%url.com%';
UPDATE wp_posts
SET post_content = REPLACE(post_content,'[PLACEHOLDER]','url.com/images')
WHERE post_content LIKE '%[PLACEHOLDER]%';

关于mysql - 替换行内的部分值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25390857/

相关文章:

mysql - 如何使用sql查询结果来使用date_add

mysql - MySQL 可以在 SELECT 中的 * 之前列出一列吗?

mysql - 从多个mysql表中选择匹配的数据+版本5.0

sql - 如何明智地按一组增加列

wordpress - WooCommerce 网址重写

php - 在 Woocommerce 中具有最大成本的基于累进数量的运输成本

mysql - 登录后如何显示每个用户的总数 - 数据库有 25,000 个用户 - 数百万行?

c# - 如何匹配 UDT T-SQL 和 C# CLR 类型?

java - Hibernate注解哪里只适用于1对多关系?

php - jquery 在 wordpress 中自动完成