替换行内的部分值

时间:2014-08-19 18:49:27

标签: 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%';

有没有办法运行单个查询并将所有必要的行更新为相同的值?

1 个答案:

答案 0 :(得分:0)

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

此查询会将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]%';

一体化,复制&amp;粘贴方便:

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]%';