根据父单元格值更新ID

时间:2014-01-29 01:01:40

标签: mysql sql

我问了一个问题,我得到了一个有效的解决方案,但我需要一点调整

这是我问的问题:

我有一个像这样的数据库

表名:人

id  name    country father_id     mother_id   HIV
52  bob     NULL    68            98          NULL
68  joe     Maui    72            14          CLEAR
53  mia     NULL    68            98          NULL 
51  robbie  NULL    68            13          NULL
98  Joyce   NULL    13            16          CLEAR

我需要对我的数据库进行查询,我将更新所有person.id与HIV'CLEARED'如果mother_id和father_id都有HIV CLEAR请注意我需要能够选择我标记孩子的单词,所以这与mother_id和father_id的值不同。

我需要数据库看起来像这样:

    id  name    country father_id     mother_id   HIV
    52  bob     NULL    68            98          CLEAR
    68  joe     Maui    72            14          CLEAR
    53  mia     NULL    68            98          CLEAR 
    51  robbie  NULL    68            13          NULL
    98  Joyce   NULL    13            16          CLEAR

解决方案我看起来像这样 - 这可行但

update person p join
       person father
       on father.id = p.father_id and father.HIV = 'Clear' join
       person mother
       on mother.id = p.mother_id and mother.HIV = 'Clear'
    set p.HIV = 'ParentsClear';

我需要一点调整才能让我知道是否

mother_id和father_id =已清除或清除

我认为这并不容易:

       update person p join
       person father
       on father.id = p.father_id and father.HIV = 'Clear' OR 'Cleared' join
       person mother
       on mother.id = p.mother_id and mother.HIV = 'Clear' OR 'Cleared'
       set p.HIV = 'ParentsClear';

1 个答案:

答案 0 :(得分:1)

虽然它基本上“一样简单”,但您需要括号,您应该将选择器放在WHERE子句而不是连接中。这使得查询在典型部署中更快。尝试像

这样的东西
UPDATE person AS child
  INNER JOIN person AS father
    ON father.id = child.father_id
  INNER JOIN person AS mother
    ON mother.id = child.mother_id 
SET child.HIV = 'ParentsClear'
WHERE
  mother.HIV IN ('Clear','Cleared')
  AND father.HIV IN ('Clear', 'Cleared')