考虑下表:
create table test1 (
id int not null,
first_name varchar(50), -- nullable
last_name varchar(50) -- also nullable
);
如果您的 UI 中未提供 first_name,您可以选择不向该字段插入数据,方法是:
insert into test1 (id, last_name) values (123, 'Smith');
或者,您可以选择为 first_name 显式提供 NULL,如下所示:
insert into test1 (id, first_name, last_name) values (123, NULL, 'Smith');
-- you could also do like this below:
-- insert into test1 values (123, NULL, 'Smith');
-- I just like providing explicit fieldnames and values
无论您选择哪种方式,只要在整个应用程序中保持一致即可。你的结果看起来是一样的:
+-----+------------+-----------+
| id | first_name | last_name |
+-----+------------+-----------+
| 123 | NULL | Smith |
| 123 | NULL | Smith |
+-----+------------+-----------+
所以 - 回答真正的问题:不要在创建表时定义显式 null。
提供 '' 或 NULL 时,请确保您保持一致。如果有些 first_name 是 '' 而有些是 NULL,那么您的 select 语句必须是:
select * from test1 where first_name is NULL or first_name is '';
这又带来了一点——如果用户输入“”(4 个空格)会怎样?您必须确保 first_name 符合某些标准,并且在输入数据库之前,first_name 的修剪版本要经过验证。如果您的数据库以 '', ' ', ' ' 等结尾,您将不得不不断运行:
select * from test1 where first_name is NULL or trim(first_name) = '';
--or--
--select * from test1 where first_name is NULL or length(trim(first_name)) = 0;
与 NULL first_name 的一致性将有助于自信地查询。