Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL How do you INSERT INTO a table with a SELECT subquery returning multiple rows?

MySQL How do you INSERT INTO a table with a SELECT subquery returning multiple rows?

  INSERT INTO Results     (      People,      names,     )     VALUES     (      (        SELECT d.id        FROM Names f        JOIN People d ON d.id  = f.id      ),       (       "Henry"      ),     ); 

I WANT to populate the new table with all results returning from this subquery. How do I do this without getting a ERROR 1242 (21000): Subquery returns more than 1 row

like image 981
stackoverflow Avatar asked Feb 23 '12 22:02

stackoverflow


People also ask

What if subquery returns multiple rows?

Multiple-row subqueries are nested queries that can return more than one row of results to the parent query. Multiple-row subqueries are used most commonly in WHERE and HAVING clauses. Since it returns multiple rows, it must be handled by set comparison operators (IN, ALL, ANY).

Can we insert a row using subquery?

Subqueries with the INSERT StatementSubqueries 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.

Which operator is used when the subquery returns multiple rows?

The IN and NOT IN operators can be used when a subquery returns multiple rows to be evaluated in comparison to the outer query. They test whether a comparison value is present in a set of values. IN is true for rows in the outer query that match any row returned by the subquery.


2 Answers

INSERT INTO Results (People, names )    SELECT d.id, 'Henry'    FROM Names f    JOIN People d ON d.id  = f.id 

Combine the static string Henry with your SELECT query.

like image 180
Ryan Avatar answered Sep 22 '22 19:09

Ryan


Here is what I've found that works well. It is a little long but many times extra data needs to be shuffled around.

Insert multiple rows into table1 from table2 with values. EXAMPLES:

INSERT INTO table1 (col1, col2, col3, col4, col5)  SELECT col1,col2,col3,col4,col5  FROM table2 t2  WHERE t2.val2 IN (MULTIPLE VALUES)  AND (Another Conditional); 

You can insert hard coded values to get insert multiple rows with repeat data:

INSERT INTO table1 (col1, col2, col3, col4, col5)  SELECT "Value", col2, col3, "1900-01-01","9999-12-31"  FROM table2 t2  WHERE t2.val2 IN (MULTIPLE VALUES)  AND (Another Conditional); 

Note that: "Value","1900-01-01","9999-12-31" will repeat across all rows inserted.

like image 40
MiggityMac Avatar answered Sep 22 '22 19:09

MiggityMac