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

≯℡__Kan透↙ 提交于 2019-12-17 07:18:33

问题


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


回答1:


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.




回答2:


INSERT INTO Results
    (
     People,
     names,
    )
    VALUES
    (
     (
       SELECT d.id
       FROM Names f
       JOIN People d ON (d.id  = f.id) limit 1
     ),

     (
      "Henry"
     ),
    );



回答3:


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.




回答4:


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



回答5:


The reason of this error (Subquery returns more than 1 row) is that you use parenthesis (). Look more careful to the best answer. It doesn't contain parethesis around subquery




回答6:


In MySql multiple values from strings can be inserted like the following avoiding duplicates. Thanks.

   insert into brand(name) select * from ( 
select 'Fender' as name 
union select 'a' 
union ..... ) t 
where not exists (select 1 from brand t2 where t2.name COLLATE latin1_general_ci = t.name COLLATE utf8mb4_unicode_ci )



回答7:


insert into ec_element(parentid,name) select elementid , 'STARTUP' from ec_element where name = 'BG';

insert statement takes values elementid from the table found with condition fulfilled and a label string.



来源:https://stackoverflow.com/questions/9422529/mysql-how-do-you-insert-into-a-table-with-a-select-subquery-returning-multiple-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!