ใช้ ALTER กับ ADD ครับ ไวยากรณ์ดังนี้:
alter table yourTableName add yourColumnName DATETIME DEFAULT NOW(), add index(yourColumnName);
สร้างตารางตัวอย่าง
mysql> create table DemoTable (
-> Id int NOT NULL AUTO_INCREMENT,
-> Name varchar(100),
-> PRIMARY KEY(Id)
-> );
Query OK, 0 rows affected (0.69 sec)
ตรวจสอบโครงสร้างตาราง
mysql> desc DemoTable;
ผลลัพธ์
+-------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+--------------+------+-----+---------+----------------+ | Id | int(11) | NO | PRI | NULL | auto_increment | | Name | varchar(100) | YES | | NULL | | +-------+--------------+------+-----+---------+----------------+ 2 rows in set (0.01 sec)
คำสั่งเพิ่มคอลัมน์และดัชนีพร้อมกัน
mysql> alter table DemoTable
-> add ArrivalDate DATETIME DEFAULT NOW(),
-> add index(ArrivalDate);
Query OK, 0 rows affected (2.05 sec)
Records: 0 Duplicates: 0 Warnings: 0
ตรวจสอบโครงสร้างอีกครั้ง
mysql> desc DemoTable;
ผลลัพธ์
+-------------+--------------+------+-----+-------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+--------------+------+-----+-------------------+----------------+ | Id | int(11) | NO | PRI | NULL | auto_increment | | Name | varchar(100) | YES | | NULL | | | ArrivalDate | datetime | YES | MUL | CURRENT_TIMESTAMP | | +-------------+--------------+------+-----+-------------------+----------------+ 3 rows in set (0.01 sec)
คำอธิบาย: คอลัมน์ ArrivalDate ได้รับค่า DEFAULT NOW() และมีดัชนี (MUL = Multiple/Non-unique index) สร้างเสร็จในคำสั่งเดียว