Use*_*841 2 postgresql datatypes date-format
我想在 PostgreSQL 数据库中保存年份 - 只是年份。我应该如何创建这个字段?有很多关于如何从日期字段中提取年份的信息,但没有关于我应该如何设置仅使用年份的表格的信息。我试过这个:
CREATE TABLE information (
id serial PRIMARY KEY,
year date NOT NULL
);
INSERT INTO "information" ("year") VALUES (2010);
Run Code Online (Sandbox Code Playgroud)
但这失败了:
ERROR: invalid input syntax for type date: "2010"
Run Code Online (Sandbox Code Playgroud)
要么使用一个简单的整数并将 BC 表示为负数:
CREATE TABLE information (
id serial PRIMARY KEY,
year integer NOT NULL
);
Run Code Online (Sandbox Code Playgroud)
或使用date限制在 1 月 1 日的 a 并2014-01-01在输入/输出中使用etc:
CREATE TABLE information (
id serial PRIMARY KEY,
year date NOT NULL,
CONSTRAINT year_must_be_1st_jan CHECK ( date_trunc('year', year) = year )
);
Run Code Online (Sandbox Code Playgroud)
哪个更合适主要取决于您的应用程序如何使用这些信息。我认为将一年表示为一个简单的整数是可以的 - 只是请不要为year integer, month integer. 使用这种方法很糟糕,并且是受限日期更合适的地方。
我倾向于使用受限制的日期,这样当需求不可避免地发生变化时,我可以更容易地适应。
| 归档时间: |
|
| 查看次数: |
7720 次 |
| 最近记录: |