ใน MySQL สามารถใช้ตัวแปรผู้ใช้ (User-defined Variable @var) ในคำสั่ง UPDATE เพื่อนำค่ามาคำนวณหรือต่อท้ายกับคอลัมน์ได้
ตัวอย่างการใช้งาน
สร้างตารางสินค้า:
mysql> create table DemoTable1349 (ProductId int NOT NULL AUTO_INCREMENT PRIMARY KEY, ProductPrice int); mysql> insert into DemoTable1349(ProductPrice) values(7644),(90843),(9083),(10000);
ข้อมูลก่อนอัปเดต:
+-----------+--------------+ | ProductId | ProductPrice | +-----------+--------------+ | 1 | 7644 | | 2 | 90843 | | 3 | 9083 | | 4 | 10000 | +-----------+--------------+
ตั้งค่าตัวแปร และอัปเดต ProductId=4 โดยบวก 500
mysql> set @AppendValue:=500; mysql> update DemoTable1349 set ProductPrice=ProductPrice+@AppendValue where ProductId=4;
ผลลัพธ์หลังอัปเดต (ProductId 4 กลายเป็น 10500)
+-----------+--------------+ | ProductId | ProductPrice | +-----------+--------------+ | 1 | 7644 | | 2 | 90843 | | 3 | 9083 | | 4 | 10500 | +-----------+--------------+
ประยุกต์ใช้:
- ต่อสตริง:
SET @suffix := '_updated'; UPDATE t SET col = CONCAT(col, @suffix) WHERE ... - คูณ/หาร:
SET @rate := 1.07; UPDATE t SET price = price * @rate WHERE ... - ใช้ค่าจาก Subquery:
SET @max_id := (SELECT MAX(id) FROM t); UPDATE t SET ref = @max_id WHERE ...