Monday, June 13, 2011

Insert values from one table to another in MySQL

Problem:
The problem was to insert values from a MySQL table into another one. In simple terms, For every 'id' in 'table_1', insert into 'table_2' the values of all the ids, name

Technology: SQL

Solution: Use INSERT INTO with SELECT

INSERT INTO table_2(id,name)
SELECT id,name FROM table_1;
More complex usage -> if you want to assign a constant value in one of the columns (here it is name) and 'id' from table_1, do like this
INSERT INTO table_2(id,name) 
SELECT id,'name' FROM table_1; 
If you want to match from two tables and store into the common table

INSERT INTO table_2(id,name,phonenum)
SELECT a.id,a.name,b.phonenum FROM table_1 a inner join table_3 b WHERE a.id=b.id;

No comments:

Post a Comment