简体   繁体   中英

Make Update with select statement in Mysql

I am trying to update for some products their category in Database. But I get an error and I don't understand where my statement is wrong. Please help. I want to find products that have in their name a specific word and after that I what to update the category for this products.

I want to select IDs from sho_posts where sho_posts.post_title contain this part of word '%Audio CD%' and after that to update the sho_term_relationships.term_taxonomy_id with value 2 where sho_term_relationships.object_id=sho_posts.id

UPDATE sho_term_relationships 
   SET term_taxonomy_id = 2
 WHERE object_id = (SELECT `id` FROM `1876522_shoping`.`sho_posts` WHERE CONVERT(`post_title` USING utf8) LIKE '%Audio CD%') 

In your WHERE clause, to find the ids to update based on the subquery results, use IN instead of =

UPDATE sho_term_relationships 
   SET term_taxonomy_id = 2
   WHERE object_id IN (
      SELECT `id` FROM `1876522_shoping`.`sho_posts` 
      WHERE CONVERT(`post_title` USING utf8) LIKE '%Audio CD%') 

You would use = only if you were certain the subquery would return a single row, it won't work if the subquery returns multiple rows. Using IN tests whether the object id is included in the subquery results.

You just need to use 'in' instead of '=' when updating multiple rows.

UPDATE sho_term_relationships SET term_taxonomy_id = 2 WHERE object_id in (SELECT id FROM 1876522_shoping . sho_posts WHERE CONVERT( post_title USING utf8) LIKE '%Audio CD%')

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