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

อัปเดตค่า NULL เป็นค่าเฉพาะใน MySQL

ใช้ WHERE column IS NULL ระบุเงื่อนไขใน UPDATE

สร้างตารางและเพิ่มข้อมูล (มี NULL)

mysql> create table DemoTable ( StudentScore int ); 
Query OK, 0 rows affected (0.47 sec)

mysql> insert into DemoTable values(89); Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(NULL); Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(45); Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values(NULL); Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(56); Query OK, 1 row affected (0.14 sec)

อัปเดต NULL → 30

mysql> update DemoTable set StudentScore=30 where StudentScore IS NULL; 
Query OK, 2 rows affected (0.34 sec)

ตรวจสอบผลลัพธ์

mysql> select * from DemoTable;
+--------------+
| StudentScore |
+--------------+
| 89           |
| 30           |
| 45           |
| 30           |
| 56           |
+--------------+
5 rows in set (0.00 sec)

ข้อสังเกต: ไม่สามารถใช้ = NULL ได้ ต้องใช้ IS NULL เสมอ