Home >Database >Mysql Tutorial >How to Efficiently Insert Data from One SQL Table to Another?

How to Efficiently Insert Data from One SQL Table to Another?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-04 21:33:39247browse

How to Efficiently Insert Data from One SQL Table to Another?

Inserting Data from One Table into Another in SQL

The question at hand involves the need to transfer data from one table (received_txts) to another (action_2_members) using only SQL. The original query attempted to achieve this by first creating a temporary table q1 containing the desired data from received_txts and then using this data as the source for the INSERT statement.

While this approach is valid, a more efficient and direct solution exists: the straightforward INSERT statement with a SELECT subquery. This allows you to directly insert data from the received_txts table into the action_2_members table based on the provided criteria.

The optimized SQL query would be:

INSERT INTO action_2_members (campaign_id, mobile, vote, vote_date)  
SELECT campaign_id, from_number, received_msg, date_received
  FROM `received_txts`
 WHERE `campaign_id` = '8'

This query eliminates the need for an intermediary table, improving both performance and clarity. It directly specifies the data to be inserted and the source table, making the code easier to understand and maintain.

The above is the detailed content of How to Efficiently Insert Data from One SQL Table to Another?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn