我有一个数据库,如下所示
表名: person
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与艾滋病病毒‘清除’,如果mother_id和father_id都有艾滋病病毒清除请注意,我需要能够选择我标记孩子的单词,所以这将不会是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如果这太复杂,我将坚持使用与父级相同的值:P
如果mother_id和father_id不清楚,我希望person.id HIV单元保持为空
请保持简单,因为我是新手:P
发布于 2014-01-29 07:13:53
下面是update语句:
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';我突然想到,您可能只想在字段为空时执行update。如果是,则向查询添加一个where p.HIV is null。
编辑:
我建议您修改您的表,以便为ParentHIV添加一个字段。我不知道你在做什么,但存在混淆个人数据和来自父母的数据的危险。
下面是一个如何使用它的示例:
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.ParentHIV = (case when father.HIV = 'Clear' and mother.HIV = 'Clear'
then 'BothClear'
when father.HIV = 'Clear' or mother.HIV = 'Clear'
then 'OneClear'
else 'NeitherClear'
end);发布于 2014-01-29 07:07:42
试试这个:
Select p.id
From person p
INNER JOIN person father ON father.id = p.father_id
INNER JOIN person mother ON mother.id = p.mother_id
WHERE father.HIV = 'Clear' AND mother.HIV = 'Clear'然后使用这些id执行UPDATE查询:
UPDATE person SET HIV = 'Clear' WHERE id IN (the result set of ids separated by commas)https://stackoverflow.com/questions/21418758
复制相似问题