简体   繁体   中英

SQL: Update multiple rows with result from same table

I'm trying to update a field (post_id) in multiple rows of a table with a value available in one row of the same table. The table is a Wordpress table wp_meta

Here is the structure of the table

meta_id  | post_id |  meta_key |  meta_value
1           16          author    "Staff"
2           16          title      "title"
3           16          old_id       250
4       17          author      "jay"
5           17          old_id     251
6       18          author      "panda"
7           18          title      "realy nice"
8           18          old_id      252
9           18          some_key    lorem"

I want this to be so that the post_id should be replaced with the old_id for that corresponding set of posts. The result should be something like this

meta_id  | post_id |  meta_key |  meta_value
1           250          author    "Staff"
2           250         title      "title"
3           250         old_id       250
4       251         author      "jay"
5           251         old_id     251
6       252         author      "panda"
7           252         title      "realy nice"
8           252         old_id      252
9           252         some_key    lorem"

This is what I'm trying, but it's wrong

UPDATE wprk_postmeta as t1
SET post_id = (SELECT t2.meta_value from  wprk_postmeta as t2 WHERE t2.meta_key='old_id' AND t2.post_id=t1.post_id)

When I run the above I get sub query returned more than one value error.

I think you want a join :

UPDATE wprk_postmeta pm JOIN
       work_postmeta pmo
       ON pm.post_id = pmo.post_id AND
          pmo.meta_key = 'old_id'
    SET post_id = pmo.meta_value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM