如何在 MySQL 中添加 NOT NULL 列?

mysqlmysqli database

您可以在创建表时添加 NOT NULL 列,也可以将其用于现有表。

案例 1 − 在创建表时添加 NOT NULL 列。语法如下

CREATE TABLE yourTableName
(
   yourColumnName1 dataType NOT NULL,
   yourColumnName2 dataType
   .  
   .
   .
   N
);

创建表的查询如下

mysql> create table NotNullAtCreationOfTable
   -> (
   -> Id int not null,
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.60 sec)

上表中,我们将Id声明为int类型,不接受NULL值。如果插入NULL值,则会出错。

错误如下

mysql> insert into NotNullAtCreationOfTable values(NULL,'John');
ERROR 1048 (23000): Column 'Id' cannot be null

插入除 NULL 之外的值。这是可以接受的

mysql> insert into NotNullAtCreationOfTable values(1,'Carol');
Query OK, 1 row affected (0.13 sec)

使用 select 语句显示表中的记录。查询如下

mysql> select *from NotNullAtCreationOfTable;

以下是输出 −

+----+-------+
| Id | Name  |
+----+-------+
|  1 | Carol |
+----+-------+
1 row in set (0.00 sec)

案例2 − 在现有表中添加一个非空列。语法如下

ALTER TABLE yourTableName ADD yourColumnName NOT NULL

创建表的查询如下

mysql> create table AddNotNull
   -> (
   -> Id int,
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (1.43 sec)

以下是使用 alter 命令在现有表中添加非空列的查询。

将列更改为非空列的查询如下。这里我们将添加具有 NOT NULL 约束的 Age 列。

mysql> alter table AddNotNull add Age int not null;
Query OK, 0 rows affected (0.44 sec)
Records: 0 Duplicates: 0 Warnings: 0

现在你可以使用 desc 命令来查看表的描述。查询如下

mysql> desc AddNotNull;

以下是输出 −

+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| Id    | int(11)      | YES  |     | NULL    |       |
| Name  | varchar(100) | YES  |     | NULL    |       |
| Age   | int(11)      | NO   |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
3 rows in set (0.08 sec)

让我们尝试向 Age 列插入 NULL 值。如果您尝试向 Age 列插入 NULL 值,您将收到错误。

插入记录的查询如下

mysql> insert into AddNotNull values(1,'John',NULL);
ERROR 1048 (23000): Column 'Age' cannot be null

现在插入另一条记录。这不会出错

mysql> insert into AddNotNull values(NULL,NULL,23);
Query OK, 1 row affected (0.22 sec)

现在您可以使用 select 语句显示表中的所有记录。查询如下

mysql> select *from AddNotNull;

以下是输出 −

+------+------+-----+
| Id   | Name | Age |
+------+------+-----+
| NULL | NULL | 23 |
+------+------+-----+
1 row in set (0.00 sec)

相关文章