MySQL INSERT INTO SELECT: Copy Data Easily

In MySQL, the SELECT INSERT statement is used to select data from one table and insert it into another table. The syntax is as follows:

INSERT INTO table2 (column1, column2, ...)
SELECT column1, column2, ...
FROM table1
WHERE condition;

This statement selects data that meet the conditions from table1 and inserts them into table2. It can be used to copy data from one table to another or insert query results into a table.

For example, we have two tables, people and new_people, with the same column names and data types. We can use a SELECT INSERT statement to copy the data from the people table where the age is over 30 to the new_people table.

INSERT INTO new_people (name, age)
SELECT name, age
FROM people
WHERE age > 30;

This will select the data that meets the conditions in the people table and insert their name and age columns into the new_people table.

In conclusion, the SELECT INSERT statement can help us to select and insert data, thereby achieving functions such as data duplication, migration, and importation.

bannerAds