Update or Insert with data from another table

Asked

Viewed 516 times

0

I have this command SQL to update the tableREQUISICOES with the table dataREQUISICOES_ATUALIZA.

Use as key to update the field numero_requisicao, but I need if not find correspondencia on the table REQUISICOES, enter a new record from the table REQUISICOES_ATUALIZA;

This one works to update:

UPDATE requisicoes a
JOIN requisicoes_atualiza b
SET a.projeto = b.projeto
WHERE a.numero_requisicao = b.numero_requisicao

And what would SQL look like for those who don’t exist?

  • What would be the new record if it does not exist?

  • If you understand about, you will be able to solve your problem: Not IN or Not EXISTS which to use?

  • If there is no corresponding request number in the Requisicoes table, I want to insert the data from the updated table... Marconi

  • 1

    I am using MYSQL!

2 answers

1

Using the NOT EXISTS. If the field numero_requisição for a declared Pacific, you can use the INSERT ... ON DUPLICATE KEY UPDATE:

INSERT INTO requisicoes (numero_requisicao, projeto)
SELECT numero_requisicao, projeto
FROM requisicoes_atualiza ra
ON DUPLICATE KEY UPDATE projeto = ra.projeto
  • Where you update this sql??

  • @Andremaia. I’m not doing update. I’m just inserting the items that don’t exist yet, which is what’s in the question, right? Theoretically 'update' was done with the other instruction of update which is already mentioned in the question.

  • I want to do in the same command, would it be possible?

  • @Andremaia, I edited the answer. See if it meets you

  • does not answer because the field is not key, and if I put I have other keys in the table.

  • Doesn’t have to be primary key, needs to be unique. If it’s not like that, then it can’t be done insert...update, make the two separate instructions.

Show 1 more comment

0

To do the Insert of what is not in your request table you can use the SQL below

INSERT INTO requisicoes (numero_requisicao, projeto)
SELECT b.numero_requisicao, b.projeto
FROM requisicoes a
LEFT JOIN requisicoes_atualiza b on a.numero_requisicao = b.numero_requisicao
WHERE a.numero_requisicao is null

I use this table a lot when I have this kind of doubt:

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.