使用單個MySQL查詢中的兩個SELECT語句將第一個表中的值插入第二個表


要使用兩個SELECT語句將第一個表中的值插入另一個表,可以使用子查詢。這將允許您僅使用單個MySQL查詢在第二個表中獲得結果。讓我們首先建立一個表:

mysql> create table DemoTable1
(
   Name varchar(100),
   Score int
);
Query OK, 0 rows affected (1.30 sec)

使用INSERT命令在表中插入一些記錄:

mysql> insert into DemoTable1 values('Chris',45);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1 values('Bob',78);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1 values('David',98);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1 values('Carol',89);
Query OK, 1 row affected (0.15 sec)

使用SELECT語句顯示錶中的所有記錄:

mysql> select *from DemoTable1;

這將產生以下輸出:

+-------+-------+
| Name  | Score |
+-------+-------+
| Chris |    45 |
| Bob   |    78 |
| David |    98 |
| Carol |    89 |
+-------+-------+
4 rows in set (0.00 sec)

以下是建立第二個表的查詢。

mysql> create table DemoTable2
(
   StudentName varchar(100),
   StudentScore int
);
Query OK, 0 rows affected (0.58 sec)

現在讓我們編寫一個MySQL查詢,使用兩個SELECT語句將第一個表中的值插入第二個表:

mysql> insert into DemoTable2(StudentName,StudentScore) values((select Name from DemoTable1 where Score=98),(select Score from DemoTable1 where Name='David'));
Query OK, 1 row affected (0.30 sec)

使用SELECT語句顯示錶中的所有記錄:

mysql> select *from DemoTable2;
+-------------+--------------+
| StudentName | StudentScore |
+-------------+--------------+
| David       |           98 |
+-------------+--------------+
1 row in set (0.00 sec)

更新於:2019年9月24日

248 次瀏覽

啟動您的職業生涯

完成課程後獲得認證

開始學習
廣告