Doubt in the insertion of data performing the relationship in another table

Asked

Viewed 33 times

0

I am trying to enter an Address in the address table and refer to a User already registered without Address in the user table, through the _id that is generated when I enter an Address. I return this _id and insert it in the column adresses_id of the User who has Cpf equal to the User who will receive this Address.

WITH new_adresses AS (
INSERT INTO adresses (cep, street, neighborhood, city, state, number_house, complement)
        VALUES ('11222333', 'Rua Qualquer', 'Bairro', 'Cidade', 'ES', 777, 'Ed. Edifício')
        RETURNING _id)
        INSERT INTO users (adresses_id)
        VALUES (SELECT _id FROM new_adresses)
        WHERE cpf = '111.222.333-00'

I’m not getting the insertion done that way. The following error message is appearing:

ERROR: syntax error at or near "SELECT"
Posição: 281
  • if the intention is to update "INSERT INTO users (adresses_id)" is incorrect, you should try an update

  • It worked, thanks for the help. I wasn’t realizing that it would have to be an UPDATE instead of an INSERT.

2 answers

0

Hello, you are closing the parentheses in the wrong place, close it after informing Cpf, getting: ... VALUES (SELECT _id FROM new_adresses WHERE Cpf = '111.222.333-00')

  • The same mistake keeps popping up. Because WHERE serves to select which user, from the user table, I will insert the _id that was returned from the inserted address.

  • Blz, I’m glad it worked out.

0


I was making a mistake using INSERT instead of UPDATE SET. The correct query is as follows:

WITH new_adresses AS (
INSERT INTO adresses (cep, street, neighborhood, city, state, number_house, complement)
        VALUES ('11222333', 'Rua do Karalho', 'Fon', 'YoCity', 'YO', 777, 'Ed. YoPredio')
        RETURNING _id)
        UPDATE users
        SET adresses_id = (SELECT _id FROM new_adresses)
 WHERE cpf = '139.127.217-00'

Browser other questions tagged

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