gpt4 book ai didi

sql - 在 postgres 中使用时间戳

转载 作者:行者123 更新时间:2023-11-29 13:17:18 24 4
gpt4 key购买 nike

我正在尝试在 postgres 中构建和填充一个表。最终产品应该看起来像这样 my goal

这些是表格应该包含的列以及我认为它们应该使用的数据类型(如果您有关于更好地拟合数据类型的建议,我想知道它们)。

  • id 整数
  • 名称 VARCHAR(60)
  • 性别 VARCHAR(1)
  • 年龄整数
  • intake_date 时间戳
  • 采用日期时间戳

我用这个命令创建了表,

pets=# CREATE TABLE cats (
id integer,name text,gender text, age integer, intake_date timestamp,
adoption_date timestamp);

然后尝试在这个命令中添加我所有的行并得到

pets=# INSERT INTO cats (id,name,gender,age, intake_date,adoption_date)
VALUES
(00001, 'Mushi', 'M', 1,2016-01-09, 2016-03-22)
(00002, 'Seashell' , 'F', 7,2016-01-09)
(00003,'Azul', 'M', 3, 2016-01-11, 2016-04-17)
(00004, 'Victoire' ,'M', 7, 2016-01-11, 2016-09-01)
(00005, 'Nala', 'F', 12016-01-12);
ERROR: syntax error at or near "("
LINE 4: (00002, 'Seashell' , 'F', 7,2016-01-09)

然后我部分意识到 postgres 会有问题,因为某些 adoption_date 列留空。所以我尝试至少添加一行

pets=# INSERT INTO cats (id,name,gender,age, intake_date,adoption_date)
VALUES
(00001,'Mushi','M', 1, 2016-01-09, 2016-03-22);

返回错误

ERROR:  column "intake_date" is of type timestamp without time zone but 
expression is of type integer
LINE 3: (00001,'Mushi','M', 1, 2016-01-09, 2016-03-22);
^
HINT: You will need to rewrite or cast the expression.

所以我的三个问题或未知数是

  1. 如何创建一个表,其中的列的时间戳数据类型在输入时留空?
  2. 我应该如何输入时间戳?
  3. 是否有更好的数据类型我应该使用

最佳答案

时间戳数据应该在单引号内传递

INSERT INTO cats (id,name,gender,age, intake_date,adoption_date)
VALUES(00001, 'Mushi', 'M', 1,'2016-01-09', '2016-03-22');

当你想插入空白值时,只需使用NULL

INSERT INTO cats (id,name,gender,age, intake_date,adoption_date)
VALUES(00002, 'Seashell' , 'F', 7,'2016-01-09',null);

像下面这样创建表(default Null 分配给插入时要留空的列)

CREATE TABLE cats1 (
id integer
,name text
,gender text
,age integer
,intake_date timestamp
,adoption_date timestamp default Null
);

关于sql - 在 postgres 中使用时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47194685/

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