如何对已创建的 MySQL 列添加 NOT NULL 约束?
使用 ALTER TABLE 可以实现这一点。我们首先创建一个表 −
mysql> create table DemoTable -> ( -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentName varchar(100) -> ); Query OK, 0 rows affected (0.86 sec)
让我们查看表的描述 −
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)
以下是对另一列“StudentName”添加 NOT NULL 约束的查询,该列最初未设置 NOT NULL −
mysql> alter table DemoTable modify StudentName varchar(100) NOT NULL; Query OK, 0 rows affected (1.57 sec) 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)
广告