如何在 MySQL 的日期时间字段中存储 NULL 值?

发布于 2024-08-09 19:59:58 字数 530 浏览 5 评论 0原文

我有一个“bill_date”字段,我希望在计费之前将其保留为空白(NULL),此时将输入日期。

我发现 MySQL 不喜欢日期时间字段中的 NULL 值。你们中有人有一个简单的方法来处理这个问题,还是我被迫使用最短日期作为“NULL 等效项”,然后检查该日期?

谢谢。

编辑添加:

好的,我确实看到 MySQL 会接受 NULL 值,但如果我使用 PHP 更新记录,它不会接受它作为数据库更新。

变量名称为 $bill_date,但如果我更新记录而不将值发送到 $bill_date,它不会将变量保留为 NULL - 我收到此错误:

Database query failed: Incorrect datetime value: '' for column 'bill_date' at row 1

I假设我需要实际发送单词 NULL,或者将其完全排除在更新查询之外,以避免此错误?我说得对吗?谢谢!!!

I have a "bill_date" field that I want to be blank (NULL) until it's been billed, at which point the date will be entered.

I see that MySQL does not like NULL values in datetime fields. Do any of you have a simple way to handle this, or am I forced to use the min date as a "NULL equivalent" and then check for that date?

Thanks.

EDITED TO ADD:

Ok I do see that MySQL will accept the NULL value, but it won't accept it as a database update if I'm updating the record using PHP.

The variable name is $bill_date but it won't leave the variable as NULL if I update a record without sending a value to $bill_date -- I get this error:

Database query failed: Incorrect datetime value: '' for column 'bill_date' at row 1

I assume I need to actually send the word NULL, or leave it out of the update query altogether, to avoid this error? Am I right? Thanks!!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

傾旎 2024-08-16 19:59:58

MySQL确实允许datetime字段使用NULL值。我刚刚测试过:

mysql> create table datetimetest (testcolumn datetime null default null);
Query OK, 0 rows affected (0.10 sec)

mysql> insert into datetimetest (testcolumn) values (null);
Query OK, 1 row affected (0.00 sec)

mysql> select * from datetimetest;
+------------+
| testcolumn |
+------------+
| NULL       | 
+------------+
1 row in set (0.00 sec)

我正在使用这个版本:

mysql> select version();
+-----------+
| version() |
+-----------+
| 5.0.45    | 
+-----------+
1 row in set (0.03 sec)

说到通过 PHP 代码插入 NULL 值,假设您正在使用准备好的语句(您绝对应该这样做),插入 NULL 值没有问题。只需通常的方式绑定您的变量以及所有 PHP 变量包含 null 值的内容将在 MySQL 中存储为 NULL。

只需确保您的 PHP 变量确实包含 NULL 而不是空字符串。

MySQL does allow NULL values for datetime fields. I just tested it:

mysql> create table datetimetest (testcolumn datetime null default null);
Query OK, 0 rows affected (0.10 sec)

mysql> insert into datetimetest (testcolumn) values (null);
Query OK, 1 row affected (0.00 sec)

mysql> select * from datetimetest;
+------------+
| testcolumn |
+------------+
| NULL       | 
+------------+
1 row in set (0.00 sec)

I'm using this version:

mysql> select version();
+-----------+
| version() |
+-----------+
| 5.0.45    | 
+-----------+
1 row in set (0.03 sec)

Speaking of inserting NULL values through PHP code, given you are using prepared statements (as you definitely should), there is no problem with inserting NULL values. Just bind your variable the usual way, and all PHP variables that contain null values will be stored as NULL in MySQL.

Just make sure that your PHP variable indeed contains NULL and not an empty string.

椒妓 2024-08-16 19:59:58

这是一个明智的观点。

空日期不是零日期。它们可能看起来一样,但其实不然。在 mysql 中,空日期值是 null。零日期值是一个空字符串 ('') 并且 '0000-00-00 00:00:00'

在空日期上“... where mydate = ''” 将失败。< br>
在空/零日期“...其中 mydate 为空”将失败。

但现在让我们变得时髦。在mysql日期中,空/零日期是严格相同的。

例如,

select if(myDate is null, 'null', myDate) as mydate from myTable where  myDate = '';
select if(myDate is null, 'null', myDate) as mydate from myTable where  myDate = '0000-00-00 00:00:00'

两者都会输出:'0000-00-00 00:00:00'。如果您使用 '' 或 '0000-00-00 00:00:00' 更新 myDate,两个选择仍然会以相同的方式工作。

在 php 中,标准 mysql 连接器将尊重 mysql 空日期类型,并且是真正的空值 ($var === null, is_null($var))。空日期将始终表示为“0000-00-00 00:00:00”。

我强烈建议仅使用空日期,或者如果可以的话仅使用空日期。 (有些系统将使用“虚拟”零日期,它们是有效的公历日期,例如 1970-01-01 (linux) 或 0001-01-01 (oracle)。

空日期在 php/mysql 中更容易。你没有但是,您必须“手动”转换 '' 中的 '0000-00-00 00:00:00' 日期以显示空字段(以存储或搜索您没有的字段)。处理零日期的特殊情况,这很好)。

插入或更新时必须小心,不要在 null 周围添加引号,否则将插入零日期而不是 null,这会导致您的错误。在搜索表单中,您需要处理“and mydate is not null”等情况,

空日期通常需要更多工作,但它们比零日期快得多。以便查询。

This is a a sensible point.

A null date is not a zero date. They may look the same, but they ain't. In mysql, a null date value is null. A zero date value is an empty string ('') and '0000-00-00 00:00:00'

On a null date "... where mydate = ''" will fail.
On an empty/zero date "... where mydate is null" will fail.

But now let's get funky. In mysql dates, empty/zero date are strictly the same.

by example

select if(myDate is null, 'null', myDate) as mydate from myTable where  myDate = '';
select if(myDate is null, 'null', myDate) as mydate from myTable where  myDate = '0000-00-00 00:00:00'

will BOTH output: '0000-00-00 00:00:00'. if you update myDate with '' or '0000-00-00 00:00:00', both selects will still work the same.

In php, the mysql null dates type will be respected with the standard mysql connector, and be real nulls ($var === null, is_null($var)). Empty dates will always be represented as '0000-00-00 00:00:00'.

I strongly advise to use only null dates, OR only empty dates if you can. (some systems will use "virual" zero dates which are valid Gregorian dates, like 1970-01-01 (linux) or 0001-01-01 (oracle).

empty dates are easier in php/mysql. You don't have the "where field is null" to handle. However, you have to "manually" transform the '0000-00-00 00:00:00' date in '' to display empty fields. (to store or search you don't have special case to handle for zero dates, which is nice).

Null dates need better care. you have to be careful when you insert or update to NOT add quotes around null, else a zero date will be inserted instead of null, which causes your standard data havoc. In search forms, you will need to handle cases like "and mydate is not null", and so on.

Null dates are usually more work. but they much MUCH MUCH faster than zero dates for queries.

〃安静 2024-08-16 19:59:58

我在 Windows 上遇到了这个问题。

这是解决方案:

要传递 '' 为 NULL,您应该禁用 STRICT_MODE(在 Windows 安装中默认启用)

顺便说一句,将 '' 传递为 NULL 很有趣。我不知道他们为什么会允许这种行为。

I had this problem on windows.

This is the solution:

To pass '' for NULL you should disable STRICT_MODE (which is enabled by default on Windows installations)

BTW It's funny to pass '' for NULL. I don't know why they let this kind of behavior.

枕头说它不想醒 2024-08-16 19:59:58

这取决于您如何声明您的表。 NULL 不允许出现在:

create table MyTable (col1 datetime NOT NULL);

但它会被允许出现在:

create table MyTable (col1 datetime NULL);

第二个是默认值,所以一定有人主动决定该列不应该为空。

It depends on how you declare your table. NULL would not be allowed in:

create table MyTable (col1 datetime NOT NULL);

But it would be allowed in:

create table MyTable (col1 datetime NULL);

The second is the default, so someone must've actively decided that the column should not be nullable.

清晨说晚安 2024-08-16 19:59:58

如果您的日期时间列不接受空值,则它可能不可为空,因此您可以使用以下命令更新该列:

ALTER TABLE your_table modify your_coloumn datetime null

并且当您想要保存空字段时,您可以保留它(不为该字段分配任何内容),或者您可以将其设置为 Null(而不是 '')

If your datetime column is not accepting null values it might be not nullable, so you can update the column using this command:

ALTER TABLE your_table modify your_coloumn datetime null

And when you want to save a null field, you can leave it alone (not assigning anything to that field), or you can set it to Null (instead of '')

风苍溪 2024-08-16 19:59:58

值得一提的是:我在尝试通过 Perl 更新 MySQL 表时遇到了类似的问题。当空字符串值(从另一个平台读取的空值转换而来)传递到日期列(下面的代码示例中的“dtcol”)时,更新将失败。我终于通过使用更新语句中嵌入的 IF 语句成功更新了数据:

    ...
    my $stmnt='update tbl set colA=?,dtcol=if(?="",null,?) where colC=?';
    my $status=$dbh->do($stmt,undef,$iref[1],$iref[2],$iref[2],$ref[0]);
    ...

For what it is worth: I was experiencing a similar issue trying to update a MySQL table via Perl. The update would fail when an empty string value (translated from a null value from a read from another platform) was passed to the date column ('dtcol' in the code sample below). I was finally successful getting the data updated by using an IF statement embedded in my update statement:

    ...
    my $stmnt='update tbl set colA=?,dtcol=if(?="",null,?) where colC=?';
    my $status=$dbh->do($stmt,undef,$iref[1],$iref[2],$iref[2],$ref[0]);
    ...
脸赞 2024-08-16 19:59:58

我刚刚发现,只要字段的默认值为 null,MySQL 就会采用 null,并且我编写特定的 if 语句并省略引号。这也适用于更新。

if(empty($odate) AND empty($ddate))
{
  $query2="UPDATE items SET odate=null, ddate=null, istatus='$istatus' WHERE id='$id' ";
};

I just discovered that MySQL will take null provided the default for the field is null and I write specific if statements and leave off the quotes. This works for update as well.

if(empty($odate) AND empty($ddate))
{
  $query2="UPDATE items SET odate=null, ddate=null, istatus='$istatus' WHERE id='$id' ";
};
节枝 2024-08-16 19:59:58

我刚刚在 MySQL v5.0.6 中进行了测试,日期时间列接受 null 没有问题。

I just tested in MySQL v5.0.6 and the datetime column accepted null without issue.

不即不离 2024-08-16 19:59:58

特别是与您收到的错误相关的是,您不能在 PHP 中对 MySQL 中的可为空字段执行类似的操作:

$sql = 'INSERT INTO table (col1, col2) VALUES(' . $col1 . ', ' . null . ')';

因为 PHP 中的 null 将等同于空字符串,这与以下内容不同: MySQL 中的 NULL 值。相反,您想要这样做:

$sql = 'INSERT INTO table (col1, col2) VALUES(' . $col1 . ', ' . (is_null($col2) ? 'NULL' : $col2). ')';

当然您不必使用 is_null 但我认为它更好地说明了这一点。使用empty()或类似的东西可能更安全。如果 $col2 恰好是一个在查询中用双引号括起来的字符串,请不要忘记 not 包含“NULL”字符串周围的字符串,否则它将无法工作。

希望有帮助!

Specifically relating to the error you're getting, you can't do something like this in PHP for a nullable field in MySQL:

$sql = 'INSERT INTO table (col1, col2) VALUES(' . $col1 . ', ' . null . ')';

Because null in PHP will equate to an empty string which is not the same as a NULL value in MysQL. Instead you want to do this:

$sql = 'INSERT INTO table (col1, col2) VALUES(' . $col1 . ', ' . (is_null($col2) ? 'NULL' : $col2). ')';

Of course you don't have to use is_null but I figure that it demonstrates the point a little better. Probably safer to use empty() or something like that. And if $col2 happens to be a string which you would enclose in double quotes in the query, don't forget not to include those around the 'NULL' string, otherwise it wont work.

Hope that helps!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文