2011-11-18 56 views
0

在我的MySQL數據庫我有兩個表中有兩個相同的字段。Mysql更新table1與表2比較

我需要更新table2中的所有記錄,其中table1具有相同的id_customer且字段不爲空。

例子:

table1的

ID |名稱|姓| id_customer |電子郵件

1|jon|jack|12|[email protected]

表2

id_customer | name |姓|電子郵件

12 | |jack|[email protected]

查詢必須更新表2加入「喬恩」上的名字

任何想法如何?

謝謝

回答

1

嘗試這一個 -

UPDATE table1 t1 
    JOIN table2 t2 
    ON t1.customer_id = t2.customer_id 
SET 
    t2.name = IF(t2.name IS NULL OR t2.name = '', t1.name, t2.name), 
    t2.email = IF(t2.email IS NULL OR t2.email = '', t1.email, t2.email), 
    t2.sur_name = IF(t2.sur_name IS NULL OR t2.sur_name = '', t1.sur_name, t2.sur_name); 
0
update table2 
set table2.name = table1.name, 
table2.email = table1.email, 
table2.sur_name = table1.sur_name 
where table2.customer_id = table1.customer_id 

我猜它可能是更好的投身於CUSTOMER_ID,如果是兩個表中可用的(因爲它是例子)。此外,如果我們需要更新table1的基礎table1,那麼我們是否可以更新所有字段,如果是,則執行上面的查詢,否則您可以看看CASE子句。

+1

我覺得您的查詢應該開始 - 「更新表1,表2 ......」 – Devart

+0

此查詢不似是寫得很好 – stefano

+0

UPDATE表1,表2是SET加工 – stefano