Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert into with multiple subqueries as values

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 ?

like image 938
Felice Pollano Avatar asked Jun 05 '12 16:06

Felice Pollano


People also ask

How subquery pass multiple values?

Multiple row subquery returns one or more rows to the outer SQL statement. You may use the IN, ANY, or ALL operator in outer query to handle a subquery that returns multiple rows. Contents: Using IN operator with a Multiple Row Subquery.

Can you use a subquery in an insert statement?

Subqueries also can be used with INSERT statements. The INSERT statement uses the data returned from the subquery to insert into another table. The selected data in the subquery can be modified with any of the character, date or number functions.

Can you have multiple subqueries?

You can specify up to 16 subqueries within a single SQL statement, and you can specify subqueries within a subquery. Subqueries run from last to first within the main SQL statement in which they appear.

How many values can a subquery return if it is used in an insert statement?

Answer: A.A single-row subquery can return a maximum of one value. Multiple-column subqueries return more than one column to the outer query.


2 Answers

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
like image 176
Triple Gilaman Avatar answered Oct 24 '22 00:10

Triple Gilaman


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...
like image 1
Russell Fox Avatar answered Oct 24 '22 01:10

Russell Fox