1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

  2. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[SQL] INSERT unique rows taken from the same table with a changed column

Discussão em 'Outras Linguagens' iniciado por Stack, Setembro 3, 2021.

  1. Stack

    Stack Membro Participativo

    I have a table table_1 in Postgres with three columns based on a Django model, ID (auto incrementing value), affiliation, and entry.

    What I need to do is take every entry where affiliation = 52, and then add an additional row with entry = query.entry and affiliation = 48. I need additional rows, not changed values. I also need to make sure that the entry + affiliation pair does not exist already.

    My latest attempt:

    do $$
    declare
    id_array int[];
    begin
    insert into id_array table_1.entry where table_1.affiliation = 52;
    for id in id_array
    loop
    if not exists (select entry from table_1 where affiliation = 48)
    then
    insert into table_1 (affiliation, entry) values (48, id);
    else
    raise notice "already exists";
    end if;
    endloop;
    end; $$


    I still get a syntax error! Any ideas? I'm at a complete loss. This is by far the most complex query I've ever tried.

    Continue reading...

Compartilhe esta Página