在 MySQL 中设置 Null
Preet Sanghavi
2022年5月13日
MySQL
MySQL NULL

在本教程中,我们旨在探索如何在 MySQL 中设置 NULL
值。
如果没有值,则必须将 MySQL 中的特定表字段更新为 NULL
。这种 NULL
值添加有助于数据存储、可访问性和分析。
如果用户没有输入,可能需要将验证表单的特定字段设置为 NULL
。MySQL 借助 UPDATE TABLE
语句帮助解决这个问题。
让我们了解这种方法是如何工作的。
在开始之前,让我们创建一个虚拟数据集以使用表 student_details
,其中包含几行。
-- create the table student_details
CREATE TABLE student_details(
stu_id int,
stu_firstName varchar(255) DEFAULT NULL,
stu_lastName varchar(255) DEFAULT NULL,
primary key(stu_id)
);
-- insert rows to the table student_details
INSERT INTO student_details(stu_id,stu_firstName,stu_lastName)
VALUES(1,"Preet","Sanghavi"),
(2,"Rich","John"),
(3,"Veron","Brow"),
(4,"Geo","Jos"),
(5,"Hash","Shah"),
(6,"Sachin","Parker"),
(7,"David","Miller");
在 MySQL 中设置 Null 值
该技术的基本语法可以说明如下。
UPDATE name_of_the_table SET column_name = NULL WHERE <condition>;
基于特定条件,让我们将 NULL
值分配给 student_details
表的 stu_lastName
列。
UPDATE student_details SET stu_lastName = NULL WHERE stu_id IN (1,2,3);
上面代码块的输出可以用以下查询来说明。
SELECT * from student_details;
输出:
stu_id stu_firstName stu_lastName
1 Preet NULL
2 Rich NULL
3 Veron NULL
4 Geo Jos
5 Hash Shah
6 Sachin Parker
7 David Miller
如上面的代码块所示,stu_id
为 1
、2
或 3
的学生已被分配给他们的姓氏 NULL
值。
因此,借助 UPDATE
语句,我们可以有效地为 MySQL 表中的特定字段设置空值。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Preet Sanghavi