2014-01-29 47 views
0

Ive得到與製作該查詢的幫助,但我需要查詢隻影響那些NOT NULL更新單元基於父ID僅當父值不爲空

我有這個問題的細胞

我有一個叫做「人」表看起來像這樣:

id name country father_id 
52 bob  NULL 68 
68 joe  Maui 72 
53 mia  NULL 68 
51 robbie NULL 68 

我現在想直接在數據庫中運行一個查詢更新所有 person.id與同一個國家作爲他們的father_id

這樣的人表看起來就像這樣:

id name country father_id 
52 bob  Maui 68 
68 joe  Maui 72 
53 mia  Maui 68 
51 robbie Maui 68 

所以我的問題是,我該怎麼辦基礎上,person.id的 father_id的國家

我得到了下面這個解決方案的更新,但如上所述,我需要更新隻影響單元格的值,而不是NULL單元格...

update person p join 
     person father 
     on p.father_id = father.id 
    set p.country = father.country; 

回答

0

添加WHERE條款

UPDATE person AS p 
     INNER JOIN person AS father 
      ON p.father_id = father.id 
    SET p.country = father.country 
WHERE p.country IS NULL 
     AND father.country IS NOT NULL 
+0

這個完美工作。謝謝。 – CMilla

0
UPDATE person AS child 
INNER JOIN person AS father ON child.father_id=father.id 
SET child.country=father.country 
WHERE child.country IS NULL;