MySQL能否自动将空字符串转换为NULL?

时间:2021-08-15 11:46:16

There is an excellent SO on MySQL empty strings versus NULL here, MySQL, better to insert NULL or empty string?, however it doesn't take in to account 'uniformity' - i.e. if you want to have just one choice in your tables (i.e. empty string OR NULL), which should it be?

MySQL空字符串上有一个很好的SO而不是这里的NULL,MySQL,最好插入NULL或空字符串?但是它没有考虑到“一致性” - 即如果你想在你的表中只有一个选择(即空字符串OR NULL),它应该是什么?

My question is, can I get MySQL to automatically store empty strings as NULLs?

我的问题是,我可以让MySQL自动将空字符串存储为NULL吗?

After reading the previous SO I am generally inclined to store NULL but the problem is that I have a lot of PHP forms with optional fields, and (when left blank) these return empty strings.

在阅读了之前的SO后,我通常倾向于存储NULL,但问题是我有很多带有可选字段的PHP表单,并且(当留空时)这些返回空字符串。

2 个解决方案

#1


28  

You can enclose your strings with NULLIF()

你可以用NULLIF()括起你的字符串

You use it like this:

你这样使用它:

NULLIF('test','') --> returns 'test'
NULLIF(''    ,'') --> returns NULL

#2


1  

Alternatively to NULLIF you could set the default to NULL and just not pass empty fields along.

对于NULLIF,您可以将默认值设置为NULL,而不是传递空字段。

#1


28  

You can enclose your strings with NULLIF()

你可以用NULLIF()括起你的字符串

You use it like this:

你这样使用它:

NULLIF('test','') --> returns 'test'
NULLIF(''    ,'') --> returns NULL

#2


1  

Alternatively to NULLIF you could set the default to NULL and just not pass empty fields along.

对于NULLIF,您可以将默认值设置为NULL,而不是传递空字段。