使用ALTER TABLE实现此目的。让我们首先创建一个表-
mysql> create table DemoTable -> ( -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentName varchar(100) -> );
让我们检查表的描述-
mysql> desc DemoTable;
这将产生以下输出-
+-------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+--------------+------+-----+---------+----------------+ | StudentId | int(11) | NO | PRI | NULL | auto_increment | | StudentName | varchar(100) | YES | | NULL | | +-------------+--------------+------+-----+---------+----------------+ 2 rows in set (0.01 sec)
这是将NOT NULL约束添加到另一列“ StudentName”的查询,该约束最初并未设置为NOT NULL-
mysql> alter table DemoTable modify StudentName varchar(100) NOT NULL; Records: 0 Duplicates: 0 Warnings: 0
让我们再次检查表的描述-
mysql> desc DemoTable;
这将产生以下输出-
+-------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+--------------+------+-----+---------+----------------+ | StudentId | int(11) | NO | PRI | NULL | auto_increment | | StudentName | varchar(100) | NO | | NULL | | +-------------+--------------+------+-----+---------+----------------+ 2 rows in set (0.00 sec)