Insert into with multiple subqueries as values

2019-05-23 10:54发布

问题:

Lets suppose I've to insert into a table with many fk, just to explain here below the wrong statement:

insert into mytable
values
(
somevalue
,somevalue
,select id from othertable1 where ...condition
,select id from othertable2 where ...condition
,select id from othertable3 where ...condition
)

so basically values to insert comes from different subqueries, is it possible to achieve such a behavior ?

回答1:

insert into mytable (columns)
select somevalue, somevalue, a.id, b.id, c.id
from
 othertable1 a
 cross join othertable2 b
 cross join othertable3 c
where
 a ... condition
 b ... condition
 c ... condition


回答2:

Can you use a select statement to do the insert?

INSERT INTO MYTABLE
SELECT (SOMEVALUE,
    SOMEVALUE,
    T1.ID,
    T2.ID
)
FROM ANOTHERTABLE T1
JOIN YETANOTHERTABLE T2
    ON T1.BLAH = T2.BLAH
WHERE condition1...