Merge two tables into a third table

Asked

Viewed 248 times

0

I need to merge two tables imagem1 and imagem2 in a third table imagens with SQL. They have exactly the same structure but with 1 query I can’t write all the data at once, so I need to make 2 queries.

I need a SQL to merge the tables into a third call imagens. The starting point is shown in the image, I can do nothing different before that point.

inserir a descrição da imagem aqui

The two tables have this structure ....

  • ID
  • IMMOVABLE
  • CODE
  • IMAGEM_G
  • Imagem_p

In imagem1 does not have the data of IMAGEM_G while in imagem2 has not IMMOVABLE and CODE.

On the third call imagens I need all this information together.

  • The id in both tables corresponds to the same image?

  • Yes, the Ids in both tables match the same record.

2 answers

3

Considering that the correspondence between the tables is by the ID column, I didn’t understand why I would need two queries. I would do so:

INSERT INTO imagens
(id, imovel, codigo, imagem_g, imagem_p)
SELECT 
    imagem1.id,
    imagem1.imovel,
    imagem1.codigo,
    imagem2.imagem_g,
    NULL -- Se tiver imagem_p em imagem2, coloque aqui
FROM imagem1
    INNER JOIN imagem2
    ON imagem2.id = imagem1.id
  • I tried the code of Updating but did not execute or error. I tried direct on phpmyadmin. It can help me to find the error?

  • Ah, I saw now that you edited the comment. Did not error or execute? Some return it gives, even if it is 0 Rows affected.

  • Looks like he’s jamming the bank and he’s not going forward or backward with the INSERT. And if I update the table imagem1 taking only the column IMAGEM_G table imagem2. It would solve my problem!!! How can I do it?

  • 1

    The @bfavaretto query is correct, but depending on the size of the tables, it might actually catch phpmyadmin. Try to run it using the terminal directly, you can resolve as there are no runtime restrictions.

0

You can just update one of the tables as the example below, of course after updating its structure.

UPDATE docs 
 INNER JOIN docs_1 
   ON docs_1.id=docs.id
SET docs.teste2=docs_1.teste;

Browser other questions tagged

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