引用相同的 table 作为 UPDATE 的目标和 MySql 中的数据源

Referencing the same table both as target of UPDATE and source of data in MySql

我想对我的本地数据库进行更新,使某些字段具有与 table 中存在的另一个字段相同的值。

我想到了这个查询:

$wpdb->prepare(
    "
    UPDATE wp_usermeta meta
    SET meta.meta_value = (
      SELECT usermeta.meta_value
      FROM wp_usermeta usermeta
      WHERE usermeta.meta_key='nickname'
      AND usermeta.user_id = %d
    )
    WHERE meta.user_id = %d
    AND meta.meta_key='first_name'
    ",
    $userId[0],
    $userId[0]
)

查询将在 PHP 循环中 运行,因此在每次迭代中 $userId 都会不同。查询是针对WordPress数据库的运行(但这应该与问题无关)。

我在尝试 运行 查询时收到以下错误:

Table 'meta' is specified twice, both as a target for 'UPDATE' and as a separate source for data

我该如何解决这个问题?

一种方法是使用join代替:

UPDATE wp_usermeta meta JOIN
       wp_usermeta meta2
       on meta.user_id = meta2.user_id and
          meta2.meta_key = 'nickname'
SET meta.meta_value = meta2.meta_value
WHERE meta.user_id = %d AND meta.meta_key = 'first_name';

我可能建议在 where 子句中添加一些内容,例如 meta.meta_value is not null,以防万一名字已经填充。但是,您似乎想要复制字段,这就是上面所做的。

 UPDATE wp_usermeta x
   JOIN wp_usermeta y
     ON y.user_id = x.user_id 
    SET x.meta_value = y.meta_value
  WHERE y.meta_key = 'nickname'
    AND x.meta_key = 'first_name'
    AND x.user_id = %d;