views:

48

answers:

3

I use the following code to copy from one table directly into another:

$transfer = $db->exec("INSERT INTO table2 SELECT * FROM table1 WHERE groupname = '$gname'");

The issue I have, however, is the ID field of both tables do not necessarily match (both auto-increment) and at times this may mean one temporary's tables ID# is higher than the final table.

I use php, pdo and mysql.

Is there any way around this?

+1  A: 

Explicity state what columns you want:

"INSERT INTO table2 (`col_1`,`col_2`) SELECT `col_1`, `col_2` FROM table1 WHERE groupname = '$gname'"
prodigitalson
@prodigitalson - I *could* but there are 54 columns. NOT fun
JM4
I never said it would be fun... or non-mind-numbing... if you set up some infrastructure to "profile" the table schema you actually automate that. of course thats more work than typing out the columns, but if youre likely to use it in other parts of the app for different things then it might be worth it. Or you could use an existing Data Access Layer like Zend_Db, Doctrine DBAL, or Creole.
prodigitalson
A: 
"INSERT INTO final_table SELECT * FROM temp_table WHERE temp_table.groupname = '$gname'"

Where's the issue here? If both are auto_increment, and like you said temp_table's id is HIGHER than perm_table, you'll end up getting the right effect.

Aditya Menon
@Aditya Menon - you just copied and pasted the exact code i mentioned i had trouble with? The final table can be updated from a number of sources, not just temp_table so in theory the final table could be at count 400 while temp is at 300 - trying to insert #301 causes error;
JM4
I am so sorry man. Yeah, pasting your same code was intentional, I did not consider the possibility of other sources adding data. Sorry, sorry.
Aditya Menon
A: 

You should also be aware that MySQL will block inserts to the select table:

http://dev.mysql.com/doc/refman/5.0/en/insert-select.html

Joshua Martell
what does that even mean "block inserts"? Are you referring to "if the primary key conflicts?"
JM4
Blocked usually refers to something waiting something else. `http://en.wikipedia.org/wiki/Blocking_(computing)` INSERT statements to the table you're SELECTing from will not complete until your `INSERT INTO .. SELECT ...` statement finishes.
Joshua Martell