2014-01-29 45 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;