ใช้ฟังก์ชัน IFNULL() หรือ IF() ร่วมกับ IS NULL เพื่อตรวจสอบและใส่ค่า Default อัตโนมัติ
ไวยากรณ์
INSERT INTO yourTableName(yourColumnName1, yourColumnName2)
VALUES('yourValue', IF(yourColumnName1 IS NULL, DEFAULT(yourColumnName2), 'yourMessage'));
ตัวอย่างการใช้งาน
สร้างตารางที่มีคอลัมน์ UserPostMessage ตั้งค่า Default:
mysql> create table Post (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> UserName varchar(10),
-> UserPostMessage varchar(50) NOT NULL DEFAULT 'Hi Good Morning !!!'
-> );
Query OK, 0 rows affected (0.67 sec)
เพิ่มข้อมูลทดสอบ:
mysql> insert into Post(UserName,UserPostMessage) values('John', if(UserName IS NULL, DEFAULT(UserPostMessage), 'Hello'));
mysql> insert into Post(UserName,UserPostMessage) values(NULL, if(UserName IS NULL, DEFAULT(UserPostMessage), 'Hello'));
mysql> insert into Post(UserName,UserPostMessage) values('Carol', if(UserName IS NULL, DEFAULT(UserPostMessage), 'Hello'));
ผลลัพธ์:
+----+----------+---------------------+ | Id | UserName | UserPostMessage | +----+----------+---------------------+ | 1 | John | Hello | | 2 | NULL | Hi Good Morning !!! | | 3 | Carol | Hello | +----+----------+---------------------+
แถวที่ 2: UserName เป็น NULL จึงใช้ค่า Default ของ UserPostMessage