Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a GROUP BY result into another table

Tags:

sql

mysql

I was migrating a field to a new table. The new table has three fields. What I tried was

INSERT INTO foo VALUES ('', (SELECT bar FROM baz GROUP BY bar), '');

This resulted in an error due to multiple rows resulting from the select.

What is the right way to do this?

like image 835
jerrygarciuh Avatar asked Nov 18 '09 02:11

jerrygarciuh


3 Answers

If I understand you correctly, you want something like:

INSERT INTO foo (col1name, col2name, col3name)
    SELECT '', bar, ''
    FROM baz
    GROUP BY bar
like image 82
Michael Petrotta Avatar answered Sep 18 '22 07:09

Michael Petrotta


Or if I'm understanding you correctly and you want one entry in the new table for every distinct bar value in the old table I think this makes that a bit clearer.

INSERT INTO foo (col2name) SELECT DISTINCT bar FROM baz

The execution plan and performance should be similiar

like image 42
MadMurf Avatar answered Sep 19 '22 07:09

MadMurf


You can try:

INSERT INTO foo 
SELECT '',bar,'' FROM baz GROUP BY bar
like image 25
LukLed Avatar answered Sep 21 '22 07:09

LukLed