如何向已创建的 MySQL 列添加 NOT NULL 约束?

mysqlmysqli database更新于 2025/9/5 8:44:17

使用 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 modified StudentName varchar(100) NOT NULL;
Query OK, 0 rows impacted (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)

相关文章


有用资源