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

a 夏天 提交于 2019-12-14 04:17:44

问题


I wanted to make an update against my local database where I'd make some of the fields have the same value as another field present in the table.

I came up with this query:

$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]
)

The query would be run in a PHP loop so on each iteration the $userId will be different. The query is run against WordPress database (but this should be irrelevant to the question).

I'm receiving the following error when attempting to run the query:

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

How could I solve this problem?


回答1:


One method is to use join instead:

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

I might suggest adding something to the where clause such as meta.meta_value is not null, just in case the first name is already populated. However, you seem to want to copy the field, which is what the above does.




回答2:


 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;


来源:https://stackoverflow.com/questions/35711343/referencing-the-same-table-both-as-target-of-update-and-source-of-data-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!