从同一个表中插入行和复制值 [英] Insert row and copy value from same table
本文介绍了从同一个表中插入行和复制值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的上一个问题的后续问题.
现在的要求是:
在表 B 中,对于每个具有 key='left'
但没有 key='right'
的 id,我需要创建一个新行key='right'
并将带有 key='left'
的行的 value_B
复制到新的 value_B
带有 key='right'
的行.
In Table B, for each id that has key='left'
but doesn't have key='right'
, I need to create a new row with key='right'
and copy value_B
of the row with key='left'
to value_B
of the new row with key='right'
.
之前
表 B
id key value_B
1500 left X20
1500 right X20
1501 left X21
1502 left X22
1502 right X22
1503 middle X23
之后
表 B
id key value_B
1500 left X20
1500 right X20
1501 left X21
1501 right X21
1502 left X22
1502 right X22
1503 middle X23
推荐答案
With NOT EXISTS
:
insert into TableB(id, `key`, value_B)
select b.id, 'right', b.value_B
from TableB b
where b.key = 'left'
and not exists (
select 1 from TableB
where id = b.id and `key` = 'right'
);
请参阅演示.
结果:
See the demo.
Results:
> id | key | value_B
> ---: | :----- | :------
> 1500 | left | X20
> 1500 | right | X20
> 1501 | left | X21
> 1501 | right | X21
> 1502 | left | X22
> 1502 | right | X22
> 1503 | middle | X23
这篇关于从同一个表中插入行和复制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文