Insert GROUP BY result into another table

I moved the field to a new table. There are three fields in the new table. What I tried was

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

This led to an error due to several rows as a result of the selection.

What is the right way to do this?

+4
source share
5 answers

If you understand correctly, you need something like:

 INSERT INTO foo (col1name, col2name, col3name) SELECT '', bar, '' FROM baz GROUP BY bar 
+15
source

Or, if I understand you correctly, and you want one record in a new table for each individual column value in the old table, I think this makes it a little clearer.

 INSERT INTO foo (col2name) SELECT DISTINCT bar FROM baz 

The execution plan and performance should be similar.

+6
source

You can try:

 INSERT INTO foo SELECT '',bar,'' FROM baz GROUP BY bar 
+4
source
 INSERT INTO foo (fieldName1,fieldName2,fieldName3) SELECT '',bar,'' FROM baz GROUP BY bar 
+4
source

Walking with Michael, another possibility would be

 INSERT INTO foo (col2name) SELECT bar FROM baz GROUP BY bar 

where col1 and col3 are defined as having a default value for an empty string.

+4
source

All Articles