简体   繁体   中英

SQL to copy values from one table to another

In Table B, for each id that doesn't have key=right , I need to create it and copy value_A to value_B .

Example:

Before state

Table A

id      value_A
1500    R20
1501    R21
1502    R22

Table B

id      key     value_B
1500    left    L20
1500    right   R20
1501    left    L21
1502    left    L22
1502    right   R22

After state

Table A

id      value_A
1500    R20
1501    R21
1502    R22

Table B

id      key     value_B
1500    left    L20
1500    right   R20
1501    left    L21
1051    right   R21
1502    left    L22
1502    right   R22

You want insert . One method uses not exists :

insert into b (id, key, value_b)
    select a.id, 'right', a.value_a
    from a
    where not exists (select 1
                      from b
                      where b.id = a.id and b.key = 'right'
                     );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM