简体   繁体   中英

How to update rows when WHERE value is a sub query with more than 1 row of results

I want to run this SQL:

UPDATE wp_postmeta 
   SET meta_value = 1.00 
 WHERE meta_key = '_test' 
   AND post_id = (SELECT post_id 
                    FROM wp_postmeta 
                   WHERE meta_value = 8032)

I was hoping it would set meta_value to 1.00 where the meta_key is _test and post_id is any of the returned post_id from the sub query: SELECT post_id FROM wp_postmeta WHERE meta_value = 8032

Upon simulating this query in phpMyAdmin it says that the sub query has more than 1 result , therefore how can I make this work?

Maybe it's not really something to do in SQL, I guess I could pull the post_id sub query results into PHP then loop through them and then do the original SQL..?

Replace = with IN :

UPDATE wp_postmeta 
SET meta_value = 1.00 
WHERE 
    meta_key = '_test' 
    AND post_id IN (SELECT post_id FROM wp_postmeta WHERE meta_value = 8032)

But as table is the same why not just:

UPDATE wp_postmeta 
SET meta_value = 1.00 
WHERE 
    meta_key = '_test' 
    AND meta_value = 8032

Error

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

can be fixed as

UPDATE wp_postmeta 
SET meta_value = 1.00 
WHERE 
    meta_key = '_test' 
    AND post_id IN (
        SELECT * FROM (
            SELECT post_id FROM wp_postmeta WHERE meta_value = 8032
        ) t
    )

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