MySQL Insert with a Select Subquery

Posted: April 5th, 2009 | Author: Rob Searles | Filed under: General | Comments

This is a post more for me than anyone else, but hopefully others out there will find it useful.

Today I had a problem in that I deleted all entries from a MySQL database table that I shouldn’t have. This table was basically a mapping table, mapping many to many relationships between two other tables. Unfortunately I didn’t have a recent backup of the database (lesson learnt there!).  Originally I thought it would be a nightmare having to put all the entries back in, then I remembered that all the mapping entries I have deleted always had another corresponding mapping entry.

The table structure is really very simple:
band_id and group_id.

I had removed all instances of group #103, however, every instance of group #103 was replicated by group #104.

All I needed to do was to re-insert the group #103 for every band_id that was mapped to group #104. A simple subquery!

Here it is:

INSERT INTO  map_band_group (band_id, group_id)
(SELECT band_id, 103 FROM map_band_group WHERE group_id = 104);

This little snippet saved many hours of work: it’s good to be lazy!

If you liked this post, please share it:
  • Digg
  • Reddit
  • Sphinn
  • Facebook
  • del.icio.us
  • YahooMyWeb
  • Furl
  • Mixx
  • Google
  • Fark
  • Live
  • MisterWong
  • StumbleUpon
  • Technorati
  • TwitThis
  • BlogMemes
  • Blogsvine
  • Ma.gnolia
  • Pownce
  • Spurl

Popular Posts


  • aryagarg
    well gud job sir
  • Thanks, glad you found it handy!

    Having to cast my mind back here, but I think the mapping table was needed as it was just a coincidence that both group 103 always had 104 mapped to an identical band, just in this case. There were a load of other groups that were mapped to bands that didn't have a corresponding group mapping.

    Also, would there be a speed issue with having a sub query and not a mapping table? TBH I'm not sure, but it's worth a thought.
  • virtualtrader
    Thanks handy post. If you can simply use a subquery here, is your mapping table really needed then?
blog comments powered by Disqus