INSERT INTO with Mysql filter

Asked

Viewed 485 times

2

I am trying to create an INSERT INTO in an X table by making a filter in table Y, but I get a syntax error. I’ve researched what could be wrong, but not found.

INSERT INTO products (
    SELECT * FROM products AS P
    WHERE P.FK_ID_QUOTE = 101
)
  • 1

    What would be the goal of putting a "Where" in the Insert?

  • I want to specify in which id of the quote table I want to add what I Filtred

  • You want to duplicate a record by changing the id?

  • if I understand the comment the idea is to change a record, not to include a new one... no?

  • No. I created a function to duplicate a quote with a new id, but I need to copy all products from the reference quote to the new quote. This query I posted is wrong. I will edit. But what I need is to copy the filter products with new id and associate the duplicate quote. In the end I want everything to be duplicated with new ids

2 answers

4


Where you are placing the query you have to specify the columns you want to copy and then comes the values that can be obtained by the selection, something like this:

INSERT INTO products (nome, valor, etc)
    SELECT nome, valor, etc FROM products AS P
    WHERE P.FK_ID_QUOTE = 101

I put in the Github for future reference.

2

The solution would be to make a subquery, as below:

I created the PESSOA_2 table, which I want to insert data into it according to the PERSON table:

inserir a descrição da imagem aqui

In this case, the query to insert in PESSOA_2 would be:

INSERT INTO PESSOA_2 (IDADE, ID_PESSOA, NOME, DATA_NASC) 
SELECT 15, ID_PESSOA, NOME, DATA_NASC FROM PESSOA WHERE IDADE = 20;

The result:

inserir a descrição da imagem aqui

Browser other questions tagged

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