MySQL如何在时间戳字段的值明确为null时使用当前时间?

huangapple go评论44阅读模式
英文:

MySQL how to use current time if value of timestamp field is explicitly null?

问题

我想要完成以下任务:

我有一个MySQL表中的字段,当提供NULL值时,应该解析为当前时间。

我按照以下步骤操作:

CREATE TABLE foo (
    bar TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    baz INT
);

-- 现在让我们插入一些数据。
INSERT INTO foo (bar, baz) VALUES (null, 2);

-- 现在让我们确保它按预期工作。
SELECT * FROM foo;

但不幸的是,它并没有按预期工作:

**********
bar  | baz
**********
null | 2

只有当我在INSERT语句中省略列的值时,它才起作用。

如何使上述INSERT语句起作用?也就是说,当值为null时,该字段应设置为默认时间。

英文:

I want to accomplish the following:

I field in a table in MySQL that, when provided with a NULL value, should resolve to the current time.

I did the following:

CREATE TABLE foo (
    bar TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    baz INT
);

-- Now let's insert something.
INSERT INTO foo (bar, baz) VALUES (null, 2);

-- Now let's make sure it works as desired.
SELECT * FROM foo;

but unfortunately it doesn't work as expected:

**********
bar  | baz
**********
null | 2

It only works when I leave off the column's value in an INSERT statement.

How can I make the above INSERT statement work? That is, the field should be set to the default time when the value is null.

答案1

得分: 2

以下是翻译好的内容:

你所询问的在SQL中仅使用声明性功能是不可能的:DEFAULT约束仅在从INSERT中省略列时使用(或者使用DEFAULT作为值) - 否则,我所知道的替换或覆盖INSERTUPDATE中的值的唯一其他方法需要使用TRIGGER(这是非声明性的,并引入了自己的问题)。

相反,为什么不将bar列设置为NOT NULL并确保所有INSERT语句都省略该列?或者更改您的INSERT语句以使用DEFAULT关键字?

就像这样:

INSERT INTO foo ( bar, baz )
VALUES ( DEFAULT, 123 )
英文:

What you're asking isn't possible using only declarative features in SQL: a DEFAULT constraint is only used when the column is omited from an INSERT (or uses DEFAULT for the value) - otherwise the only other way (that I'm aware-of) to replace or override values in an INSERT or UPDATE requires using a TRIGGER (which is non-declarative and introduces problems of its own).

Instead, why not make bar a NOT NULL column and ensure all INSERT statements omit that column? Or change your INSERT statements to use the DEFAULT keyword?

Like so:

INSERT INTO foo ( bar, baz )
VALUES ( DEFAULT, 123 )

huangapple
  • 本文由 发表于 2023年6月21日 23:36:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76524988.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定