Multiple Inserts with a Subquery
Posted on March 20th, 2008 by Greg Allard in MySQL |
Inserting multiple rows into a table is simple.
INSERT INTO table1 (id) VALUES (1), (2)
But what if you want to use a subquery to replace the explicit query with something more dynamic. This should be possible, however, searching the internet didn’t get me (or my colleagues) any closer to figuring this out. The obvious attempt of replacing (1), (2) with (subquery) resulted in the error your subquery returns multiple records
In the end we discovered that removing VALUES from the query gave the desired effect.
INSERT INTO table1 (id) (SELECT id FROM table2)
Executing the above query will insert a row into table1 for every result returned by the subquery.
I use webfaction to host a lot of my django projects. It has an easy setup that will get you developing quickly and a great community of talented programmers. There is also a quick setup for rails, wordpress, and a lot more.
Related posts:
- Careful with Numeric Data Types in MySQL TINYINT can be set to length of 4, but that doesn’t mean the max value is 9999. A tiny int...
- Conditions on Count or Sum in MySQL When selecting count, sum, or some other aggregate function, the value isn’t determined until after the WHERE clause so a...
- Tips for MySQL to PostgreSQL Switch If you’ve decided to move a few tables from MySQL to PostgreSQL, these few tips might help. I won’t get...
For the last six years, Greg Allard has been a web developer for UCF.
Over the years,