我应该使用 NULL 还是空字符串来表示表列中没有数据?

2022-01-06 00:00:00 null database mysql

Null 或空字符串 -- 在表示表列中没有数据时,哪个比另一个更好?(我特别使用 MySQL,但我认为这是独立于系统的.)使用一个比另一个有主要的优点/缺点,还是仅仅是程序员的偏好?

Null or empty string -- is one better than the other to represent no data in a table column? (I specifically use MySQL, but I'm thinking this is system-independent.) Are there major advantages/disadvantages to using one over the other, or is it simply programmer preference?

推荐答案

我非常不同意那些说无条件使用 NULL 的人.允许一列为 NULL 会引入一个额外的状态,如果您将列设置为 NOT NULL,则不会有这种状态.如果您不需要附加状态,请不要这样做.也就是说,如果你想不出空字符串的含义和null的含义之间的区别,那就把列设置为NOT NULL,用空字符串来表示空.用两种不同的方式表示同一件事是个坏主意.

I strongly disagree with everyone who says to unconditionally use NULL. Allowing a column to be NULL introduces an additional state that you wouldn't have if you set the column up as NOT NULL. Do not do this if you don't need the additional state. That is, if you can't come up with a difference between the meaning of empty string and the meaning of null, then set the column up as NOT NULL and use empty string to represent empty. Representing the same thing in two different ways is a bad idea.

大多数告诉您使用 NULL 的人还举了一个例子,其中 NULL 的含义与空字符串不同.在这些例子中,他们是对的.

Most of the people who told you to use NULL also gave an example where NULL would mean something different than empty string. And in those examples, they are right.

然而,在大多数情况下,NULL 是一种不必要的额外状态,它只会迫使程序员不得不处理更多情况.正如其他人提到的,Oracle 不允许这种额外的状态存在,因为它将 NULL 和空字符串视为同一件事(不可能在 Oracle 中不允许为 null 的列中存储空字符串).

Most of the time, however, NULL is a needless extra state that just forces programmers to have to handle more cases. As others have mentioned, Oracle does not allow this extra state to exist because it treats NULL and empty string as the same thing (it is impossible to store an empty string in a column that does not allow null in Oracle).

相关文章