Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL INSERT with multiple nested SELECTs

Is a query like this possible? MySQL gives me an Syntax error. Multiple insert-values with nested selects...

INSERT INTO pv_indices_fields (index_id, veld_id)
VALUES
('1', SELECT id FROM pv_fields WHERE col1='76' AND col2='val1'),
('1', SELECT id FROM pv_fields WHERE col1='76' AND col2='val2')
like image 936
netiul Avatar asked Sep 27 '11 10:09

netiul


People also ask

Can we use insert and select together?

You can use a select-statement within an INSERT statement to insert zero, one, or more rows into a table from the result table of the select-statement. The select-statement embedded in the INSERT statement is no different from the select-statement you use to retrieve data.

Can you insert multiple values in MySQL?

Insert multiple rows in MySQL with the help of “values”. You can enclose the values with parentheses set with comma separation. The syntax is as follows to insert multiple rows in MySQL.

Is select faster than insert?

SELECT'. Because the 'INSERT … SELECT' inserts data into an existing table, it is slower and requires more resources due to the higher number of logical reads and greater transaction log usage. However, providing the query hint to lock the entire destination table, the two statements perform exactly the same.

What is the difference between insert into and select into?

INSERT INTO SELECT vs SELECT INTO: Both the statements could be used to copy data from one table to another. But INSERT INTO SELECT could be used only if the target table exists whereas SELECT INTO statement could be used even if the target table doesn't exist as it creates the target table if it doesn't exist.


2 Answers

I've just tested the following (which works):

insert into test (id1, id2) values (1, (select max(id) from test2)), (2, (select max(id) from test2));

I imagine the problem is that you haven't got ()s around your selects as this query would not work without it.

like image 100
Thor84no Avatar answered Sep 29 '22 00:09

Thor84no


When you have a subquery like that, it has to return one column and one row only. If your subqueries do return one row only, then you need parenthesis around them, as @Thor84no noticed.

If they return (or could return) more than row, try this instead:

INSERT INTO pv_indices_fields (index_id, veld_id)   
   SELECT '1', id 
   FROM pv_fields 
   WHERE col1='76' 
   AND col2 IN ('val1', 'val2')

or if your conditions are very different:

INSERT INTO pv_indices_fields (index_id, veld_id)
    ( SELECT '1', id FROM pv_fields WHERE col1='76' AND col2='val1' )
  UNION ALL
    ( SELECT '1', id FROM pv_fields WHERE col1='76' AND col2='val2' )
like image 27
ypercubeᵀᴹ Avatar answered Sep 29 '22 01:09

ypercubeᵀᴹ