MySQL Insert Query
In
this post we will know about MySQL Insert Query by using select query.
There are multiple ways to insert data in a table as shown below.
INSERT INTO table_name (col1,col2) VALUES(val1,val2);
OR
INSERT INTO table_name (col1,col2) VALUES(row1_val1,row1_val2),(row2_val1,row2_val2),(row3_val1,row3_val2);
In the same way we can use the select the query to insert the data from one table to another table as shown below.
INSERT INTO table1 (field1, field2)
SELECT col1 AS field1, col2 AS field2 FROM table2 WHERE id=15;
In MySQL
we have another feature i.e., INSERT..ON DUPLICATE KEY.. useful when we
are have duplicate key the values will be updated as shown in the sample
below.
INSERT INTO table1 (field1, field2)
SELECT col1 AS field1, col2 AS field2 FROM table2 WHERE id=15;
ON DUPLICATE KEY UPDATE field
field1 = VALUES(field1),
field1 = VALUES(field1);
No comments :
Post a Comment