首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Mysql根据其他两条记录的值更改单元格值

Mysql根据其他两条记录的值更改单元格值
EN

Stack Overflow用户
提问于 2014-01-29 06:59:24
回答 2查看 79关注 0票数 0

我有一个数据库,如下所示

表名: person

代码语言:javascript
复制
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相同的值。

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

代码语言:javascript
复制
    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

EN

回答 2

Stack Overflow用户

发布于 2014-01-29 07:13:53

下面是update语句:

代码语言:javascript
复制
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添加一个字段。我不知道你在做什么,但存在混淆个人数据和来自父母的数据的危险。

下面是一个如何使用它的示例:

代码语言:javascript
复制
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);
票数 3
EN

Stack Overflow用户

发布于 2014-01-29 07:07:42

试试这个:

代码语言:javascript
复制
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查询:

代码语言:javascript
复制
UPDATE person SET HIV = 'Clear' WHERE id IN (the result set of ids separated by commas)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21418758

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档