2016-04-25 97 views
0

我有一個SQL查詢來計算我需要使用UPDATE語句更新其信息的確切數量。但它包含一些複雜的連接,我不確定如何在UPDATE語句中重新創建該語句。任何幫助?將SELECT語句轉換爲其對應的UPDATE語句

我的查詢是在這裏:

select distinct c.id 
from implementation.tt_ngma_exclude_emails nee 
join customer c on nee.util_account_id = c.util_internal_id 
join customer_notification_contact cnc on cnc.customer_id = c.id 
left join customer_notification_contact_audit cnca on cnca.customer_id = c.id 
where cnc.changed_on = '2015-11-15 12:30:02'; 

的這裏的目標是在customer_notification_contact表更新特定領域,而不是從我選擇的實施表。我想設置email領域的數控工作臺爲NULL到處是cnc.customer_id = c.id

這裏是我的嘗試,但它似乎並沒有工作:

UPDATE customer_notification_contact cnc 
(select distinct cnc.customer_id opower_customer_id 
from implementation.tt_ngma_exclude_emails nee 
join customer c on nee.util_account_id = c.util_internal_id 
join customer_notification_contact cnc on cnc.customer_id = c.id 
where cnc.changed_on = '2015-11-15 12:30:02' 
) T2 
SET cnc.email = NULL 
WHERE cnc.customer_id = T2.opower_customer_id; 
+1

連接將保持不變。只要將'select ... from ...'改爲'update ...' –

+0

對不起,我認爲原來的問題含糊不清。我想更新customer_notification_contact。不是implementation.tt_ngma_exclude_emails。 – Asif

回答

1

請這給一試只需將T1.SOME_COLUMN(最後第2行)替換爲您要更新的實際列名即可。我添加了GROUP BY CNC.CUSTOMER_ID,因爲當您更新多行時,您應該知道該計數屬於哪個客戶。除非你試圖用相同的計數更新所有的行,我假設你沒有試圖去做。

UPDATE customer_notification_contact T1, 
(
select count(distinct c.id) AS MY_COUNT,CNC.CUSTOMER_ID 
from implementation.tt_ngma_exclude_emails nee 
join customer c on nee.util_account_id = c.util_internal_id 
join customer_notification_contact cnc on cnc.customer_id = c.id 
left join customer_notification_contact_audit cnca on cnca.customer_id = c.id 
where cnc.changed_on = '2015-11-15 12:30:02' 
GROUP BY CNC.CUSTOMER_ID 
)T2 
SET T1.SOME_COLUMN = T2.MY_COUNT 
WHERE T1.CUSTOMER_ID = T2.CUSTOMER_ID 

UPDATE看到更新後的問題,這應該是查詢。

UPDATE customer_notification_contact T1, 
(
select distinct c.id 
    from implementation.tt_ngma_exclude_emails nee 
    join customer c on nee.util_account_id = c.util_internal_id 
    join customer_notification_contact cnc on cnc.customer_id = c.id 
    left join customer_notification_contact_audit cnca on cnca.customer_id = c.id 
    where cnc.changed_on = '2015-11-15 12:30:02' 
)T2 
SET T1.EMAIL = NULL 
WHERE T1.CUSTOMER_ID = T2.id 
+0

我認爲這非常接近我所需要的。我已經更新了我的問題,以便更清楚一點。 – Asif

+0

然後嘗試添加',T1.email = NULL'到第二個最後一行的末尾,在更改T2子查詢之後,就像你擁有它..你可以做到這一點 –

+0

在底部看到我更新的答案部分 –