简体   繁体   English

从另一个表更新

[英]Update from another table

I have a table that I need to update with data from another table. 我有一个表,我需要使用另一个表中的数据进行更新。 Problem is there is no foreign key relationship between the two tables. 问题是两个表之间没有外键关系。 However, there is a third table that has the relationship. 但是,有第三个表具有这种关系。

Here are the tables: 以下是表格:

Parent table: 父表:

ParentKey     ParentField
-------------------
 p1           aaa
 p2           bbb
 p3           ccc

Child table: 儿童桌:

ChildKey     ChildField
-------------------
 c1           ccc
 c2        
 c3

Relationship table: 关系表:

ParentKey    ChildKey
-------------------
 p1          c2
 p2          c3
 p3          c1

Here's what I want to do... If the Child table does not have a value in ChildField then I want to update the ChildField with the value of the corresponding ParentField. 这是我想要做的...如果Child表在ChildField中没有值,那么我想用相应的ParentField的值更新ChildField。 So basically my final result should look like this: 所以基本上我的最终结果应如下所示:

Child table: 儿童桌:

ChildKey     ChildField
-------------------
 c1           ccc
 c2           aaa
 c3           bbb

Even without a foreign key, you can still join the two tables together to do the update: 即使没有外键,您仍然可以将两个表连接在一起进行更新:

update      child
set         childfield = parent.parentfield
from        child
inner join  Relationship on Relationship.ChildKey = Child.ChildKey
INNER JOIN  Parent on PArent.ParentKey = Relationship.ParentKey
WHERE       Child.ChildField IS NULL

This should work in Microsoft SQL Server. 这应该在Microsoft SQL Server中工作。 Pretty sure it will work elsewhere as well 很确定它也可以在其他地方使用

This should work for you; 这对你有用;

UPDATE ChildTable ct SET ct.ChildField = 
    (SELECT MAX(ParentField) FROM ParentTable pt 
    INNER JOIN RelationshipTable rt ON rt.ParentKey=pt.ParentKey 
    WHERE rt.ChildKey=ct.ChildKey)
WHERE ct.ChildField IS NULL 

If you have an empty ChieldField as an empty string rather than NULL , try 如果您将空的ChieldField作为空字符串而不是NULL ,请尝试

UPDATE ChildTable ct SET ct.ChildField = 
    ISNULL((SELECT MAX(ParentField) FROM ParentTable pt 
    INNER JOIN RelationshipTable rt ON rt.ParentKey=pt.ParentKey 
    WHERE rt.ChildKey=ct.ChildKey),'')
WHERE ct.ChildField=''

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

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