Tuesday, September 9, 2014

Copy one table to another table (or same table) and update fields




Copy field1 and field2 in  table1 to table2 and update field3 as 'John' in MySQL
Insert into table2 (field1, field2, field3) select field1, field2, 'John' from table1;

  We can do the same in same table  if primarykey is AUTO_INCREMENT:

Insert into table1 (field1, field2, field3) select field1, field2, 'John' from table1 WHERE primarykey=1;

if primarykey is  not AUTO_INCREMENT, we can assign a new primary key such as 666:

Insert into table1 (primarykey, field1, field2, field3) select  666, field1, field2, 'John' from table1 WHERE primarykey=1;

No comments:

Post a Comment