简体   繁体   中英

MySQL update using inner join on a nested query

I'm trying to do this: look up a resource_id from a table items , which has asset_id and resource_id , and use it to set the resource_id field in another table, elements , which also has asset_id and resource_id .

UPDATE t1 SET t1.resource_id = t2.resource_id 
FROM elements t1 INNER JOIN
( SELECT asset_id, resource_id 
  FROM items 
  WHERE resource_id is not null
  GROUP BY asset_id ) t2 
ON t1.asset_id = t2.asset_id; 

I'm getting the very vague message:

ERROR 1064 (42000): You have an error in your SQL syntax; check the 
manual that corresponds to your MySQL server version for the 
right syntax to use near 'FROM elements t1 INNER JOIN
( SELECT asset_id, resource_id 
  FROM items' at line 2

This is in MySQL 5.6.27. Can anyone see what i'm doing wrong?

Thanks, Max

As the error says, your syntax is wrong. Try this:

UPDATE elements as t1  
INNER JOIN
( SELECT asset_id, resource_id 
  FROM items 
  WHERE resource_id is not null
  GROUP BY asset_id ) t2 
ON t1.asset_id = t2.asset_id
SET t1.resource_id = t2.resource_id 

UPDATE elements AS t1,
(SELECT asset_id, resource_id FROM items WHERE resource_id IS NOT NULL GROUP BY asset_id ) AS t2 SET t1.resource_id = t2.resource_id WHERE t1.asset_id = t2.asset_id;

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