简体   繁体   中英

SQL update over multiple tables

I have a database that has some data coming from an external source, and some that is manually entered locally.

There's an items table, with the main product info. This table includes a source column to show if it was manually entered or external. If it was manual, the source column will be NULL -- otherwise, it's the unique id of the item in the external source.

There's also an images table, with an item_id column that's keyed to the ID of the items table. The external images also get the source set to the unique ID of the item, and the item_id is temporarily set as the same unique ID.

Here's the problem: after I do an external data refresh, I need to update the local image table and set the images.item_id to the item ID in the local table. I do a query like this:

UPDATE image_table  
SET image_table.item_id = 
(SELECT id from items WHERE items.source = image_table.source AND items.source IS NOT NULL)

I expected this to only update those images where the row in the items table is NOT NULL -- however, while it works as expected for the external info, it also sets the local images item_id to 0.

Is there a better way to do this?

You'll need a WHERE condition in your UPDATE query, not in the sub-query. Otherwise the table will be updated regardless of the result of your sub-query.

For example:

UPDATE `image_table`
SET `image_table`.`item_id` = 
(SELECT `id` FROM `items` WHERE `items`.`source` = `image_table`.`source` 
                       AND `items`.`source` IS NOT NULL)
WHERE EXISTS (SELECT id FROM `items` WHERE `items`.`source` = `image_table`.`source` 
                       AND `items`.`source` IS NOT NULL)

There may be a better way, that doesn't include two identical sub-queries... But that's the first thing that comes to my mind.

There's an alternative answer here I think - update table with data from other table if not null?

UPDATE
`image_table` INNER JOIN `items` ON `image_table`.`source` = `items`.`source`
 SET `image_table`.`item_id` = `items`.`id`
 WHERE `items`.`source` IS NOT NULL

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