Skip to content
Advertisement

Insert two or more values at once from not related tables

I want to insert at once, all values from one table’s column, with max value of another table, these tables are not connected with each other.

Let’s simplify it to the maximum, tableA consists of

id
1
2
3
4
5

tableB consist of

id
10
11
12
13
14
15

TableC is

 id, external_id

Following query definitely is not going to work but I have no other idea how to solve it

INSERT INTO tablec (id, external_ids) values ((SELECT max(id) from tablea), (select id from tableb))

Of course manually inserting max value is not a solution (like select 101, id from tableb)

Extected result should be

id, external_id
5, 10
5, 11
5, 12
5, 13
5, 14
5, 15

Advertisement

Answer

INSERT INTO tablec (id, external_ids)
select (SELECT max(id) from tablea), id 
from tableb;
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement