gpt4 book ai didi

mysql - 将 NULL 值插入 postgreSQL 中的 TIMESTAMP 字段

转载 作者:行者123 更新时间:2023-11-29 14:16:34 34 4
gpt4 key购买 nike

我在 MySQL 中有以下数据库模式,我已经使用 ORM 在 PostgreSQL 中复制了它:

CREATE TABLE IF NOT EXISTS users (
id BIGINT NOT NULL DEFAULT NEXTVAL ('users_seq'),
email VARCHAR(255) NOT NULL DEFAULT '',
password VARCHAR(255) NOT NULL DEFAULT '',
last_name VARCHAR(255) NOT NULL DEFAULT '',
first_name VARCHAR(255) NOT NULL DEFAULT '',
created TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)

);

我正在尝试执行以下查询

INSERT INTO users (id, email, password,first_name, last_name, created, updated)
VALUES (1, 'user@gmail.com', 'pass', 'user', 'user', NULL, NULL);

这会导致错误

ERROR:  null value in column "created" violates not-null constraint

预期的行为是在值为 NULL 的情况下具有当前时间戳,并且它在 MySQL 中有效

我正在使用 PostgreSQL 10。我是否缺少任何配置或者 Postgres 不支持此配置?

最佳答案

NULL 与“默认”不同。

当您在要插入的值列表中指定 NULL 时,Postgres 将尝试将 NULL 插入到表的该列中。如果存在阻止这种情况发生的约束,例如列上的 NOT NULL 说明符,插入将失败。

但是,如果您未指定该列的值,Postgres 将为该列插入默认值,或者如果未指定默认值,则插入NULL

因此,由于您在这两列上都有 DEFAULT 值,您可以这样写:

INSERT INTO users (id, email, password,first_name, last_name)
VALUES (1, 'user@gmail.com', 'pass', 'user', 'user');

这实际上意味着与此相同:

INSERT INTO users (id, email, password,first_name, last_name, created, updated)
VALUES (1, 'user@gmail.com', 'pass', 'user', 'user', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);

请注意,拥有一个既接受 NULL 又具有默认值的列是完全合法的。如果尝试插入 NULL 总是插入默认值,这将是不可能的(或者,至少,不必要的复杂)。

关于mysql - 将 NULL 值插入 postgreSQL 中的 TIMESTAMP 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46766279/

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