gpt4 book ai didi

mysql - 将字段留空更好还是用空值填充它更好?

转载 作者:可可西里 更新时间:2023-11-01 07:48:07 25 4
gpt4 key购买 nike

我有一个表,其中包含名为 first_name 的列。用户不强制填写,有时用户将其留空。现在我想知道:将 null 值定义为默认值是否更好?

最佳答案

考虑下表:

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 时,只要确保你是一致的。如果一些 first_name 是 '' 而一些是 NULL,您的选择语句必须是:

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 的一致性将有助于自信地查询。

关于mysql - 将字段留空更好还是用空值填充它更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34520033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com