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

386
Visualizações
MySQL if exists update values else insert

I am creating an application that stores a students attendance.

I am creating the database that will store this attendance and I am stuck on the mySQL query.

I want the query to search for the 'lecture name' and the 'user_id' (foreign key from other database) and if that exists increment the students attendance to the lecture (attended++ and total++)

So far I have this:

    INSERT INTO `attendance`(`attendance_id`, `module_code`, `lecture_name`, 
`attended`, `total`, `user_id`) VALUES ("null","test","TEST",1,1,1)
   ON DUPLICATE KEY UPDATE 
 attended = attended+1,total = total+1                                                                                              

This will insert a new row but for the ON DUPLICATE, there is no way to pass the primary key in to check for a 'duplicate'

I was wondering if there is another way to do this in MySQL other than ON DUPLICATE KEY, or if anyone can help me out.

Here is a screenshot of the database. For example see the 'Operations Research' was created when it should of incrememented the values. This is because I have no way of adding the primary key into the SQL query.

I would appreciate any help towards this, Thanks.

screenshot of the database

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The use of null in double quotes is troubling. So, I think you should write the query as:

INSERT INTO `attendance`(`module_code`, `lecture_name`, `attended`, `total`, `user_id`)
    VALUES ('test', 'TEST', 1, 1, 1)
    ON DUPLICATE KEY UPDATE attended = attended + 1, total = total + 1 ;   

For this to work, you seem to want a unique index on (lecture_name, user_id).

Your data model does seem suspicious because the table is repeating lecture_name on multiple rows. It seems to me that you would want a lectures table and to use lecture_id in this table.

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