简体   繁体   English

通过多个表进行SQL更新

[英]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. 有一个items表,其中包含主要产品信息。 This table includes a source column to show if it was manually entered or external. 该表包括一个source列,以显示它是手动输入还是外部输入。 If it was manual, the source column will be NULL -- otherwise, it's the unique id of the item in the external source. 如果是手动的,则source列将为NULL否则,它是外部源中项目的唯一ID。

There's also an images table, with an item_id column that's keyed to the ID of the items table. 还有一个images表,其中有一个item_id列,该列键入items表的ID。 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. 外部图像还将source设置为项目的唯一ID,并且item_id暂时设置为相同的唯一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. 这是问题所在:刷新外部数据后,需要更新本地图像表,并将images.item_id设置为本images.item_id中的项目ID。 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. 我希望这只会更新items表中的行NOT NULL那些图像-但是,尽管它按外部信息的预期工作,但它还将本地图像item_id为0。

Is there a better way to do this? 有一个更好的方法吗?

You'll need a WHERE condition in your UPDATE query, not in the sub-query. 您将在UPDATE查询中而不是子查询中需要WHERE条件。 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? 我认为这里还有一个替代答案- 如果不是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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM