2014-10-28 74 views
0

我有兩個表,即profiletable_1,profile是父表,table_1是子表。我有一個email列在這兩個表中,我想要做的是例如'[email protected]'在子表列email應更新父列表列record的每列與1其中父email列是[email protected]更新父表

在where語句中,我使用兩個表的主鍵來完成它,但由於它們不相同,所以會導致錯誤。

update profile 
    set record= (
       select table_1.record 
       from Table_1 
       where profile.profile_id = Table_1.profile_id 
      ) 

,但是當我用下面這一個,我知道會工作,它給我一個錯誤"Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >="

update profile 
    set record = (
       select table_1.record 
       from Table_1 
       where profile.email = Table_1.email 
      ) 

請我如何與電子郵件列的更新工作,但不是主鍵列

+0

查詢必須只返回一行,可能與TOP 1 – mxix 2014-10-28 20:18:04

+0

更新的聯接。 – Mihai 2014-10-28 20:19:24

回答

2

如果記錄是功能依賴於電子郵件,然後導出一組電子郵件,記錄和使用,爲您更新

with s as (select distinct email, record from table1) 
update t 
set record = s.record 
from profile t 
join s on s.email = t.email 

如果S,電子郵件/ - & GT;然後記錄你從加入中得到的記錄不能保證

0

我想這是你可能會想:

update P 
set P.record= T.record 
from profile P 
Inner Join Table_1 T 
    ON P.profile_id = T.profile_id 

任何行i與P中的ProfileId相匹配的P將得到它的「記錄」列,並用T的「記錄」列中的值更新。

您可以修改此以使用JOIN中的其他列。您還可以在代碼的SET部分添加多個要更新的列。

+0

上面的代碼工作正常,但問題是,兩個表的profile_id都有不同的記錄,所以我想使用電子郵件,他們都是相同的更新 – blay 2014-10-28 20:21:56

+0

@blay所以,你有任何專欄JOIN或不? – Mihai 2014-10-28 20:23:13

+0

我有,那就是電子郵件。但是有了它,它會給出錯誤「Subquery返回的值超過1,當子查詢出現時,這是不允許的= =,<, <= , >,> =」 – blay 2014-10-28 20:26:31

0

由於這是一個父子表,你必須有一些加入條件。 我認爲你需要在上面的答覆中提到的查詢的末尾添加一個WHERE條件:

 update P 
     set P.record= T.record 
     from profile p 
     Inner Join Table_1 T 
     ON (Since parent-child, you must have a joining condition) 
     where p.email = t.email