批量更新 MySQL table 与来自另一个 table 的数据连接

Bulk update MySQL table with data concatenated from another table

这不是 WordPress 特有的,但值得注意的是它是我正在使用的 WP 数据库...

我需要为所有 post_type='appearance' 条目更新 posts table 值 post_title。当前 post_title 以所需名称开头,但以 "appearance [some #]" 结尾。所以,from "appearance" 到最后需要删除,并且需要用 meta_value from table postmeta where meta_key = _place_id and post_id 等于 ID 来自 posts table.

例如:有一个 post,ID 102,标题为 "John Doe appearance 102"。在postmetatable,其中meta_key = _place_idpost_id = 102meta_value = 108。因此,最终结果将是 post_title = John Doe 108.

这对我来说太复杂了,但我想加入是必要的。我认为两个单独的查询是有意义的。所以,类似于:

UPDATE posts

SET post_title = TRIM(TRAILING ' appearance %' FROM post_title)

WHERE post_type='appearance'

UPDATE posts

left join postmeta on
    posts.ID= postmeta.post_id
set
    posts.post_title = CONCAT(posts.post_title, " ", postmeta.meta_value WHERE postmeta.meta_key = '_place_id')

您可以使用 SUBSTRING_INDEX():

在单个查询中执行此操作
UPDATE posts p
LEFT JOIN postmeta pm
    ON p.ID = pm.post_id
SET p.post_title = CONCAT(SUBSTRING_INDEX(p.post_title, 'appearance', 1), pm.meta_value)
WHERE pm.meta_key = '_place_id'

采用 SUBSTRING_INDEX('John Doe appearance 102', 'appearance', 1) 会 return 在 appearance 出现之前 一切,即 John Doe(带有 space 最后)。然后,我们可以简单地连接 meta_value.