SQL - How to make multiple INSERTs in a table with the result of a SELECT * of another table in a query

2
Hello, I would like to know how to make multiple INSERTs in a table with the result of a SELECT of all ids of another table table that are not as foreign key in the first table.

I already have the SELECT query with LEFT JOIN:

SELECT id FROM exemplo ex LEFT JOIN outra out ON ex.id = out.exemplo_id where out.exemplo_id IS NULL

This returns all the n IDs of the other table that are not in the first one, what I want is to do type a repeat structure that will execute INSERTs n times.

    
asked by anonymous 30.10.2017 / 14:28

1 answer

1

You do not need this, you can just do the select right after the insert, making it the value, below an example:

INSERT INTO table2
SELECT * FROM table1
WHERE condition;

Just have them have the same case arguments, you can not choose any of the two, like this:

INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition;

So the insert will be done automatically.

EDIT

If you want to use just one of the fields, simply put the other values manually like this:

INSERT INTO table2 (column1, column2, column3, ...)
SELECT 'Valor manual varchar', 5, column3, ...
FROM table1
WHERE condition;

In this way only the column three will be pulled out of the query and the rest will be replayed the inserted text.

    
30.10.2017 / 16:34