我正在尝试清理MySQL中的一些数据,但我不确定修复以下问题的最有效方法。我有三列A、B和C,它们经常具有相同的值。如果A和B相同,或者A和C相同,那么如果可能的话,我想用非空值填充另一个选项。B&C不影响A的值。例如:
-------------------
|A |B |C |
-------------------
|1 |2 |3 |
|1 |2 |NULL |
|2 |5 |8 |
|2 |NULL |8 |
|3 |NULL |9 |
|3 |NULL |NULL |
-------------------在上面的示例中,第2行的C列应该填充3,第4行的B列应该是5。当我只有两个选项时,我们将相应地填充。因此,行6,列C应该是9,而行5列B和行6列B都保持为NULL。我如何编写一个脚本来解决这个问题,如果B或C不为空,那么我们可以根据表中的其他值来填充它?谢谢。
发布于 2014-02-18 00:28:34
这有点复杂,但您可以在一条update语句中完成:
update table t left outer join
table tc
on t.a = tc.a and t.b = tc.b and tc.c is not null left outer join
table tb
on t.a = tb.a and t.c = tb.c and tb.b is not null
set t.c = coalesce(t.c, tc.c),
t.b = coalesce(t.b, tb.b);此查询根据您指定的规则执行自联接以查找新值。每个join都会引入一个值。如果有多个匹配行,则从多个行中选择一个任意值。
您可以先运行一个select,看看会发生什么:
select *
from table t left outer join
table tc
on t.a = tc.a and t.b = tc.b and tc.c is not null left outer join
table tb
on t.a = tb.a and t.c = tb.c and tb.b is not null;
set c = (case when c is null
then (select c from https://stackoverflow.com/questions/21834074
复制相似问题