sql在另一列上使用链接设置默认值

qjp7pelc  于 2021-08-01  发布在  Java
关注(0)|答案(2)|浏览(322)

我正在尝试使用postgresql创建表:

  1. create table words
  2. (
  3. id bigint default nextval('words_sequence') primary key,
  4. english varchar(255) not null,
  5. word_type varchar(255) not null,
  6. created date not null,
  7. plus_one_day date default (created + interval '1 day'),
  8. plus_two_days date default (created + interval '2 day'),
  9. plus_five_days date default (created + interval '5 day'),
  10. plus_ten_days date default (created + interval '10 day'),
  11. plus_two_weeks date default (created + interval '15 day'),
  12. plus_four_weeks date default (created + interval '30 day'),
  13. plus_six_weeks date default (created + interval '45 day'),
  14. plus_three_months date default (created + interval '90 day'),
  15. plus_six_months date default (created + interval '180 day'),
  16. user_id bigint not null,
  17. deleted boolean not null default false
  18. );

我想在另一列上引用几个列,但我的方法 default (created + interval 'n day') 不起作用。如何将列的值与“created”列关联起来?
p、 我不能使用“now()”方法,因为“created”可以是将来的日期

dz6r00yl

dz6r00yl1#

你不能进去 DEFAULT :
https://www.postgresql.org/docs/current/sql-createtable.html
default子句为列定义中出现的列指定一个默认数据值。该值是任何无变量表达式(特别是,不允许交叉引用当前表中的其他列)。也不允许子查询。默认表达式的数据类型必须与列的数据类型匹配。
您需要使用 ON INSERT 触发。
我刚刚记得的一个新特性是生成列。这在postgres 12+中提供:
https://www.postgresql.org/docs/current/ddl-generated-columns.html
5.3. 生成的列
“生成的列是一个特殊的列,它总是从其他列计算…”
阅读上面的整个链接,因为这里有一些警告。如果你在12号公路上,那还是另一条路要走。

zyfwsgd6

zyfwsgd62#

你可以用 STORED 像阿德里安提供的生成列。请参见:
postgresql中的计算列/计算列/虚拟列/派生列
但是不要将函数相关的值实现为单独的列。这只是冗余数据,使表膨胀,浪费存储和缓存/ram,降低整体性能。尤其是当派生值的计算非常简单时,就像您的示例中那样。
它通常更简单、更便宜、更安全、更方便地计算这些值。 VIRTUAL 生成的列可能是一个完美的解决方案。但这些还没有实施(截至13日)。
使用 VIEW :

  1. CREATE TABLE words (
  2. id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY -- Postgres 10+
  3. , user_id bigint NOT NULL
  4. , created date NOT NULL
  5. , deleted boolean NOT NULL DEFAULT false
  6. , english text NOT NULL -- varchar(255) ?
  7. , word_type text NOT NULL
  8. );
  9. CREATE VIEW words_plus AS
  10. SELECT id, english, word_type, created -- optionally rearrange columns
  11. , created + 1 AS plus_one_day --
  12. , created + 2 AS plus_two_days
  13. , created + 5 AS plus_five_days
  14. -- etc.
  15. , user_id, deleted
  16. FROM words;

① 使用合适的 bigserial 或者 IDENTITY 列。请参见:
自动递增表列
② 博士后 varchar(255) 通常是误会。请参见:
我应该为varchar列添加任意长度限制吗?
③ 同时,我还重新排列了表列以节省更多的存储空间。请参见:
postgresql中空间的计算与节省
当然,完全可选。然后可以根据需要重新排列视图中的列序列。
④ 在postgres中,只需添加一个 integer 给你的 date 添加天数。更简单,更便宜。相关:
如何使用postgresql确定上个月的最后一天?

展开查看全部

相关问题