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

ตั้งค่า Default Value ให้คอลัมน์ใน MySQL

ใช้คำสั่ง ALTER TABLE ... MODIFY ... DEFAULT เพื่อตั้งค่าค่าเริ่มต้นให้คอลัมน์

ตัวอย่างการใช้งาน

1. สร้างตาราง

mysql> create table DemoTable (Age int);

2. ตั้งค่า Default เป็น 18

mysql> alter table DemoTable MODIFY Age int DEFAULT 18;

3. ตรวจสอบโครงสร้าง

mysql> desc DemoTable;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| Age   | int(11) | YES  |     | 18      |       |
+-------+---------+------+-----+---------+-------+

4. ทดสอบแทรกข้อมูลไม่ระบุค่า

mysql> insert into DemoTable values(19);
mysql> insert into DemoTable values();      -- ใช้ Default
mysql> insert into DemoTable values(20);
mysql> insert into DemoTable values();      -- ใช้ Default

ผลลัพธ์

+------+
| Age  |
+------+
| 19   |
| 18   |  <-- Default
| 20   |
| 18   |  <-- Default
+------+

รูปแบบอื่นๆ

-- ตั้งค่า DEFAULT ตอนสร้างตาราง
CREATE TABLE DemoTable (Age INT DEFAULT 18);

-- ใช้ DEFAULT ใน INSERT
INSERT INTO DemoTable (Age) VALUES (DEFAULT);

-- ลบ DEFAULT
ALTER TABLE DemoTable ALTER Age DROP DEFAULT;

ชนิดข้อมูลที่รองรับ DEFAULT

  • ตัวเลข, วันที่, สตริง: รองรับค่าคงที่
  • TIMESTAMP / DATETIME: รองรับ CURRENT_TIMESTAMP (MySQL 5.6+)
  • ไม่รองรับ: ฟังก์ชัน (ยกเว้น CURRENT_TIMESTAMP), Subquery