ใช้ Subquery ใน WHERE clause ของ UPDATE
สร้างตารางและเพิ่มข้อมูล
mysql> create table DemoTable ( Id int, Name varchar(20) ); Query OK, 0 rows affected (0.82 sec)
mysql> insert into DemoTable values(100,'Chris'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values(250,'David'); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable values(150,'Mike'); Query OK, 1 row affected (0.12 sec)
คิวรี่ UPDATE ใช้ Subquery หา Id สูงสุด
mysql> update DemoTable
-> set Name='Robert'
-> where Id in
-> (
-> select * from ( select max(Id) from DemoTable ) tbl1
-> );
Query OK, 1 row affected (0.27 sec)
Rows matched: 1 Changed: 1 Warnings: 0
ผลลัพธ์หลังอัปเดต
mysql> select * from DemoTable;
+------+--------+ | Id | Name | +------+--------+ | 100 | Chris | | 250 | Robert | | 150 | Mike | +------+--------+ 3 rows in set (0.00 sec)
เทคนิค: MySQL ไม่อนุญาต UPDATE ตารางเดียวกันกับ Subquery โดยตรง | ใช้ select * from (subquery) as alias ห่อหุ้มเพื่อสร้าง derived table | ทำให้ UPDATE ทำงานได้