2014-01-28 25 views
0

我試圖在單個查詢中更新多個表,但我使用的似乎沒有做任何更新。在一個查詢中更新2個表時,兩個表中都不存在相似的數據

UPDATE table1,table2 SET table1.name='John Doe',table2.name='John Doe' 
WHERE table1.id=1 and table2.id = 1; 

問題是,具有相同ID的行可能不會出現在兩個表中。我如何在這種情況下進行更新?

在這種情況下,id 1存在於table1中,但不存在於table2中。

EDIT 的想法是在兩個表中的更新數據,即使id不在表1或表2

實施例存在:

id is present in table1 but not in table2 -> Update table1. 

id is present in table2 but not table1 -> update table2. 

id is present in both table1 and table2 update both. 

id is not present in either tables -> do nothing 

回答

1

嘗試此,

UPDATE table1 
     LEFT JOIN table2 
      ON table1.id = table2.id 
SET table1.name = 'John Doe', 
     table2.name = 'John Doe' 
WHERE table1.id = 1 
+0

我從來沒有想過這是可能的..thx的提示 – Charlesliam

+0

我測試了t他的,但是如果id = 1的行在兩個表中都不存在,這仍然不起作用。 – jmenezes

+0

使用'LEFT JOIN'而不是'INNER JOIN' –

相關問題