Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

INSERT จากตารางแรกไปตารางที่สองด้วย SUBQUERY สองตัวใน MySQL

ใช้ Subquery ใน VALUES() ดึงค่าจากตารางแรกมาใส่ตารางที่สองในคำสั่งเดียว

ตารางแรก: DemoTable1

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

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)

ตารางที่สอง: DemoTable2

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

คิวรี INSERT พร้อม 2 Subqueries

mysql> insert into DemoTable2(StudentName,StudentScore) 
values((select Name from DemoTable1 where Score=98),
       (select Score from DemoTable1 where Name='David'));

ผลลัพธ์

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

เงื่อนไข: Subquery ต้องคืนค่าเพียง 1 ค่า (single row, single column)