Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

187
Visualizações
update all table x rows with insert id from table y

I've got table x with many existing rows

x ( id, name)

I've got a new table y, which is currently empty, (all fields have default values)

y ( id, uuid )

I've updated x with a new column y_id

x ( id, name, y_id )

I want to populate y for every row in x, and then associate x with y via y.id

This is as close as I've got but this sets all rows of x to have the same y.id.

with ys as (
  insert into y(uuid) values(default)
  returning id
)
update x set y_id = ys.id
from ys
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You want to populate "y" for every value of "x". But then you don't have a way to connect the tables. But . . .

with ys as (
  insert into y
      select   -- this is empty on purpose to put in only default values
      from x;
  returning id
)
update x
    set y_id = yy.id
    from (select x.*, row_number() over (order by x_id) as seqnum
          from x
         ) xx join
         (select ys.*, row_number() over (order by y_id) as seqnum
          from ys
         ) yy
         on xx.seqnum = yy.seqnum
where x.x_id = xx.x_id;

What does this do? The CTE inserts a row into y with default values for every row in x. The insert then adds a sequence number to the x's and y's so they can be aligned, one row to one row. That value is then used for the update.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda