简体   繁体   中英

SQL update row based on another row

I have a wordpress database table called "wp_postmeta"

It looks like this (simplified)

wp_postmeta

Here is what I want to do in english, hopefully someone can help me translate this to an actual SQL statement.

if meta_key(address) LIKE "%Portland%", update meta_value(post_city_id) to be 7,17" where the post_id's are the same.

So in the end it would look like: 在此处输入图片说明

I tried this, but no rows selected when executed.

UPDATE wp_postmeta
SET wp_postmeta_bak.meta_value = "7,17"
WHERE wp_postmeta.meta_key = "post_city_id"
AND
wp_postmeta.meta_key = "address" AND wp_postmeta.meta_value LIKE "%Portland"

I read in another questions here about using temporary table, but thats above my pay grade.

You're not getting any results because you're telling the code two different exclusive things:

1) where meta_key = "post_city_id" AND

2) where same column = "address".

From what I can see, it's either one or the other. You can't have both. It's probably a typo.

 WHERE wp_postmeta.meta_key = "post_city_id"
 AND
 wp_postmeta.meta_key = "address" 

 AND wp_postmeta.meta_value LIKE "%Portland"

Ahhh, the mysterious and wonderful wp_postmeta key/value store sows more mystery and wonder. You need a self-join to correlate the postmeta rows that relate to the same post_id values as each other.

You need to update the right side of a self-joined table.

  UPDATE wp_postmeta a
    JOIN wp_postmeta b  ON a.post_id = b.post_id
                       AND b.meta_key = 'address'
                       AND b.meta_value LIKE '%Portland%'
     SET a.meta_value = '7,17'
   WHERE a.meta_key = 'post_city_id'

The JOIN will yield an empty resultset unless all three of the ON criteria match. Once it yields a nonempty result set, it will update the correct rows.

Before you do this update, you can test that it's choosing the right rows with this query.

  SELECT a.meta_id, a.post_id, a.meta_key, a.meta_value,
         b.meta_value AS address
    FROM wp_postmeta a
    JOIN wp_postmeta b  ON a.post_id = b.post_id
                       AND b.meta_key = 'address'
                       AND b.meta_value LIKE '%Portland%'
   WHERE a.meta_key = 'post_city_id'

The rows in post_meta that will be updated have the meta_id values shown in this result set.

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