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

192
Visualizações
How to update data with duplicate values using Knex?

Let's say I have this array of data:

const ids = [
  '7d8206d2-74bc-4b90-a237-37f92486cde4',
  'e594fe7f-d529-4a2f-ab24-ffc4e102268c',
  '7d8206d2-74bc-4b90-a237-37f92486cde4'
]

As you can see, there are duplicates ids and when I want to update it like that:

        await knex("products")
            .increment("purchasesCount")
            .whereIn("id", ids) 

In my purchasesCount column I can see values (1, 1), but it should be (2, 1) because of duplicate ids. Is there a way to fix it?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The simplest solution is to issue one query per one purchase, as follows:

for (const id of ids) {
  await knex("products").increment("purchasesCount").where({ id: id });
}

If this is impossible for some reason (e.g. performance), then you have 2 options:

  1. Do in-memory bucketing and count how many of each ID you got. Then, do a bunch of increments with .whereIn("id", idsWithThisCountOnly). So, in the example above you'd do 2 updates, one for all ids which were found only once in the array and one for all ids which were doubled. You'll probably need a Map of id => count for counting duplicates, and will need to invert it later into the form of count => idsWithThisCountOnly[].
  2. Do not store counts in the database at all. Store only the IDs, duplicated, and use GROUP BY with COUNT when retrieving the data. This should offer better write performance (INSERTs are usually faster than UPDATEs), but at an increased storage size and slower reads.

Option 2. may be preferrable if you already have a "transactions" or "sales" table with line-items and are accessing the summary data infrequently.

about 4 years ago · Juan Pablo Isaza 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