我在 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/