MySQL - 插入数据到选择结果



MySQL Insert Into Select 语句

在 MySQL 中,**INSERT INTO... SELECT** 语句用于将一个或多个行从现有表添加到目标表。

此语句是两个不同语句的组合:INSERT INTO 和 SELECT。

  • MySQL INSERT INTO 语句是数据库管理中常用的命令,它只需要表名和要插入表中的值。但是,务必确保插入的数据与表列的结构和数据类型匹配。
  • SELECT 语句用于从现有的数据库表中获取数据。

当上述语句一起使用时,SELECT 语句首先从现有表中获取数据,然后**INSERT INTO** 语句将检索到的数据插入到另一个表(如果它们具有相同的表结构)。

语法

以下是使用 insert into select 语句的语法:

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

在执行以下查询之前,我们必须考虑以下一些重要事项:

  • 在我们即将插入数据的数据库中,必须已经存在一个表。
  • 源表和目标表都必须匹配其结构。

示例

首先,让我们使用以下查询创建一个名为**CUSTOMERS**的表:

CREATE TABLE CUSTOMERS (
   ID INT NOT NULL,
   NAME VARCHAR(20) NOT NULL,
   AGE INT NOT NULL,
   ADDRESS CHAR (25),
   SALARY DECIMAL (18, 2),
   PRIMARY KEY (ID)
);

以下查询将 7 条记录插入到上面创建的表中:

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES 
(1, 'Ramesh', 32, 'Ahmedabad', 2000.00 ),
(2, 'Khilan', 25, 'Delhi', 1500.00 ),
(3, 'Kaushik', 23, 'Kota', 2000.00 ),
(4, 'Chaitali', 25, 'Mumbai', 6500.00 ),
(5, 'Hardik', 27, 'Bhopal', 8500.00 ),
(6, 'Komal', 22, 'Hyderabad', 4500.00 ),
(7, 'Muffy', 24, 'Indore', 10000.00 );

执行以下查询以检索 CUSTOMERS 表中的所有记录:

Select * From CUSTOMERS;

以下是 CUSTOMERS 表:

ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00

将所需数据从一个表插入到另一个表

我们可能会遇到一些情况,我们只想将少量记录添加到另一个表中。这可以通过使用 WHERE 子句选择查询返回的所有行数来实现。

示例

在此之前,让我们再创建一个名为**CUSTOMERS_copy**的表,其结构与之前创建的 CUSTOMERS 表类似:

CREATE TABLE CUSTOMERS_copy (
   ID INT AUTO_INCREMENT,
   NAME VARCHAR(20) NOT NULL,
   AGE INT NOT NULL,
   ADDRESS CHAR (25),
   SALARY DECIMAL (18, 2),
   PRIMARY KEY (ID)
);

在以下查询中,我们尝试从 CUSTOMERS 表中获取记录并将其插入到 CUSTOMERS_copy 表中。

INSERT INTO CUSTOMERS_copy (ID, NAME, AGE, ADDRESS, SALARY)
SELECT ID, NAME, AGE, ADDRESS, SALARY FROM CUSTOMERS
WHERE AGE >= 25;

输出

上面程序的输出如下所示:

Query OK, 4 rows affected (0.01 sec)
Records: 4  Duplicates: 0  Warnings: 0	

验证

要确认年龄在 25 岁或以上来自“CUSTOMERS”表的记录是否已插入到目标表“CUSTOMERS_copy”中,请执行以下查询:

SELECT * FROM CUSTOMERS_copy;

以下是年龄在 25 岁或以上的记录:

ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00

使用 LIMIT 插入行

使用 MySQL LIMIT 子句,我们可以指定应添加到目标表的查询行数。

示例

在继续之前,让我们首先使用以下查询截断**CUSTOMERS_copy**表中的所有行:

TRUNCATE TABLE CUSTOMERS_copy;

现在,我们将使用 LIMIT 子句插入 CUSTOMERS 表中按 AGE 排序的前 3 条记录:

INSERT INTO CUSTOMERS_copy (ID, NAME, AGE, ADDRESS, SALARY)
SELECT ID, NAME, AGE, ADDRESS, SALARY FROM CUSTOMERS
ORDER BY AGE LIMIT 3;

输出

上面程序的输出如下所示:

Query OK, 3 rows affected (0.01 sec)
Records: 3  Duplicates: 0  Warnings: 0

验证

执行以下查询以验证记录是否反映在 CUSTOMERS_copy 表中:

SELECT * FROM CUSTOMERS_copy;

以下是这些记录:

ID NAME AGE ADDRESS SALARY
3 Kaushik 23 Kota 2000.00
6 Komal 22 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00

将一个表的所有列插入到另一个表

我们还可以将一个表中的每一列插入到另一个表中。为此,以下是语法:

INSERT INTO table2
SELECT * FROM table1

在插入所有记录之前,首先使用以下语句截断 CUSTOMERS_copy 表中的所有行:

TRUNCATE TABLE CUSTOMERS_copy;

在下面的查询中,我们尝试将 CUSTOMERS 表中的所有列添加到 CUSTOMERS_copy 表中:

INSERT INTO CUSTOMERS_copy SELECT * FROM CUSTOMERS;

输出

所有列已插入,没有错误。

Query OK, 7 rows affected (0.01 sec)
Records: 7  Duplicates: 0  Warnings: 0

验证

我们可以使用 SELECT 语句检索其内容来验证更改是否反映在 CUSTOMERS_copy 表中。

SELECT * FROM CUSTOMERS_copy;

以下是 CUSTOMERS_copy 表:

ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00

使用客户端程序进行 INSERT INTO SELECT

除了使用 MySQL 查询执行 INSERT INTO ... SELECT 语句之外,我们还可以使用 Node.js、PHP、Java 和 Python 等客户端程序来实现相同的结果。

语法

以下是各种编程语言中此操作的语法:

要通过 PHP 程序将数据从一个 MySQL 表插入到另一个 MySQL 表中,我们需要使用 **mysqli** 函数 **query()** 执行“INSERT INTO SELECT”语句,如下所示:

$sql = "INSERT INTO new_tutorials_tbl SELECT * FROM tutorials_tbl WHERE tutorial_id = 2";
$mysqli->query($sql);

要通过 Node.js 程序将数据从一个 MySQL 表插入到另一个 MySQL 表中,我们需要使用 **mysql2** 库的 **query()** 函数执行“INSERT INTO SELECT”语句,如下所示:

sql = "INSERT INTO Agentdemo(ID, NAME, GENDER, AGE) SELECT ID, NAME, GENDER, AGE FROM Agent WHERE GENDER = 'Male'";
con.query(sql);  

要通过 Java 程序将数据从一个 MySQL 表插入到另一个 MySQL 表中,我们需要使用 **JDBC** 函数 **executeUpdate()** 执行“INSERT INTO SELECT”语句,如下所示:

String sql = "INSERT INTO Agentdemo(ID, NAME, GENDER, AGE) SELECT ID, NAME, GENDER, AGE FROM Agent WHERE GENDER = \"Male\"";
st.executeUpdate(sql);

要通过 Python 程序将数据从一个 MySQL 表插入到另一个 MySQL 表中,我们需要使用 MySQL **Connector/Python** 的 **execute()** 函数执行“INSERT INTO SELECT”语句,如下所示:

sql = "INSERT INTO new_tutorials_tbl 
(tutorial_id, tutorial_title, tutorial_author, submission_date) 
SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl"
insert_into_select_query = sql
cursorObj.execute(insert_into_select_query)

示例

以下是程序:

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$dbname = 'TUTORIALS';
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if($mysqli->connect_errno ) {
   printf("Connect failed: %s
", $mysqli->connect_error); exit(); } //printf('Connected successfully.
'); $q = "SELECT * FROM new_tutorials_tbl"; if($res = $mysqli->query($q)){ printf("Select query executed successfully..!\n"); printf("The table 'new_tutorials_tbl' records before insert into select query: \n"); while($r = mysqli_fetch_array($res)){ print_r ($r); } } $sql = "INSERT INTO new_tutorials_tbl SELECT * FROM tutorials_tbl WHERE tutorial_id = 2"; if($result = $mysqli->query($sql)){ printf("Insert into select query executed successfully..! \n"); } $q = "SELECT * FROM new_tutorials_tbl"; if($res = $mysqli->query($q)){ printf("Select query executed successfully..!\n"); printf("The table 'new_tutorials_tbl' records after insert into select query: \n"); while($r = mysqli_fetch_array($res)){ print_r ($r); } } if($mysqli->error){ printf("Failed..!" , $mysqli->error); } $mysqli->close();

输出

获得的输出如下:

Select query executed successfully..!
The table 'new_tutorials_tbl' records before insert into select query:
Array
(
    [0] => 1
    [tutorial_id] => 1
    [1] => Java Tutorial
    [tutorial_title] => Java Tutorial
    [2] => new_author
    [tutorial_author] => new_author
    [3] =>
    [submission_date] =>
)
Insert into select query executed successfully..!
Select query executed successfully..!
The table 'new_tutorials_tbl' records after insert into select query:
Array
(
    [0] => 1
    [tutorial_id] => 1
    [1] => Java Tutorial
    [tutorial_title] => Java Tutorial
    [2] => new_author
    [tutorial_author] => new_author
    [3] =>
    [submission_date] =>
)
Array
(
    [0] => 2
    [tutorial_id] => 2
    [1] => PHP Tut
    [tutorial_title] => PHP Tut
    [2] => unknown2
    [tutorial_author] => unknown2
    [3] => 2023-08-12
    [submission_date] => 2023-08-12
)  
var mysql = require('mysql2');
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "Nr5a0204@123"
});

  //Connecting to MySQL
  con.connect(function (err) {
  if (err) throw err;
  console.log("Connected!");
  console.log("----------------------------------------");

  //Selecting a Database
  sql = "USE TUTORIALS"
  con.query(sql);

  sql = "CREATE TABLE Agent (ID int NOT NULL,NAME varchar(20) NOT NULL,GENDER varchar(20) NOT NULL,AGE int NOT NULL,PRIMARY KEY(ID));"
  con.query(sql);

  sql = "INSERT INTO Agent VALUES (1,'Msd', 'Male', 21), (2,'Virat', 'Male', 23), (3,'Perry', 'Female', 24), (4,'Smiti', 'Female', 18), (5,'Rose', 'Female', 23);"
  con.query(sql);

  sql = "SELECT * FROM Agent;"
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log(result);
    console.log("-------------------------------------------------------");
  });

  sql = "CREATE TABLE Agentdemo(ID int NOT NULL,NAME varchar(50) NOT NULL,GENDER varchar(20) NOT NULL,AGE int NOT NULL,PRIMARY KEY(ID));"
  con.query(sql);

  //Inserting required data from one table to another 
  sql = "INSERT INTO Agentdemo(ID, NAME, GENDER, AGE) SELECT ID, NAME, GENDER, AGE FROM Agent WHERE GENDER = 'Male'";
  con.query(sql);

  sql = "SELECT * FROM Agentdemo;"
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log(result);
  });
});        

输出

产生的输出如下:

Connected!
----------------------------------------
[
  { ID: 1, NAME: 'Msd', GENDER: 'Male', AGE: 21 },
  { ID: 2, NAME: 'Virat', GENDER: 'Male', AGE: 23 },
  { ID: 3, NAME: 'Perry', GENDER: 'Female', AGE: 24 },
  { ID: 4, NAME: 'Smiti', GENDER: 'Female', AGE: 18 },
  { ID: 5, NAME: 'Rose', GENDER: 'Female', AGE: 23 }
]
-------------------------------------------------------
[
  { ID: 1, NAME: 'Msd', GENDER: 'Male', AGE: 21 },
  { ID: 2, NAME: 'Virat', GENDER: 'Male', AGE: 23 }
]
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class InsertIntoSelect {
  public static void main(String[] args) {
    String url = "jdbc:mysql://127.0.0.1:3306/TUTORIALS";
    String user = "root";
    String password = "password";
    ResultSet rs;
    try {
      Class.forName("com.mysql.cj.jdbc.Driver");
            Connection con = DriverManager.getConnection(url, user, password);
            Statement st = con.createStatement();
            //System.out.println("Database connected successfully...!");
            String sql = "SELECT * FROM Agent";
            rs = st.executeQuery(sql);
            System.out.println("Agent table records: ");
            while(rs.next()) {
              String id = rs.getString("Id");
              String name = rs.getString("Name");
              String gender = rs.getString("Gender");
              String age = rs.getString("Age");
              System.out.println("Id: " + id + ", Name: " + name + "Gender: " + gender + ", Age: " + age);
            }
            String sql1 = "SELECT * FROM Agentdemo";
            rs = st.executeQuery(sql1);
            System.out.println("Agentdemo table before after insert into select: ");
            while(rs.next()) {
              String id = rs.getString("Id");
              String name = rs.getString("Name");
              String gender = rs.getString("Gender");
              String age = rs.getString("Age");
              System.out.println("Id: " + id + ", Name: " + name + "Gender: " + gender + ", Age: " + age);
            }
            //now let use the insert into select query
            String sql2 = "INSERT INTO Agentdemo(ID, NAME, GENDER, AGE) SELECT ID, NAME, GENDER, AGE FROM Agent WHERE GENDER = \"Male\"";
            st.executeUpdate(sql2);
            String sql3 = "SELECT * FROM Agentdemo";
            rs = st.executeQuery(sql3);
            System.out.println("Agentdemo table after after insert into select: ");
            while(rs.next()) {
              String id = rs.getString("Id");
              String name = rs.getString("Name");
              String gender = rs.getString("Gender");
              String age = rs.getString("Age");
              System.out.println("Id: " + id + ", Name: " + name + "Gender: " + gender + ", Age: " + age);
            }
    }catch(Exception e) {
      e.printStackTrace();
    }
  }
}        

输出

获得的输出如下所示:

Agent table records: 
Id: 1, Name: MsdGender: Male, Age: 21
Id: 2, Name: ViratGender: Male, Age: 23
Id: 3, Name: PerryGender: Female, Age: 24
Id: 4, Name: SmitiGender: Female, Age: 18
Id: 5, Name: RoseGender: Female, Age: 23
Agentdemo table before after insert into select: 
Agentdemo table after after insert into select: 
Id: 1, Name: MsdGender: Male, Age: 21
Id: 2, Name: ViratGender: Male, Age: 23
import mysql.connector
#establishing the connection
connection = mysql.connector.connect(
    host='localhost',
    user='root',
    password='password',
    database='tut'
)
cursorObj = connection.cursor()
insert_into_select_query = "INSERT INTO new_tutorials_tbl (tutorial_id, tutorial_title, tutorial_author, submission_date) SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl"
cursorObj.execute(insert_into_select_query)
connection.commit()
print("Data inserted into new table successfully.")
cursorObj.close()
connection.close()        

输出

以下是上述代码的输出:

Data inserted into new table successfully.
广告