SQL:如何创建具有自动计算列值的表?

问题描述 投票:0回答:1

问题:尝试创建一个名为“duration”的列,该列根据“start_time”列和“end_time”列的差异自动插入其值。

SQL 方言:PostgreSQL

这是我尝试过的

CREATE TABLE my_table_example (
    start_time BIGINT,
    end_time BIGINT,
    duration BIGINT AS DIFFERENCE(start_time, end_time)
)

问题:使用 SQL DDL 如何自动计算其他两列的差值作为 SQL 'CREATE TABLE' 语句中的值?

目标:SQL 插入语句中的表应该是什么样子的示例

insert into my_table_example (1, 2)

insert into my_table_example (2, 5)

insert into my_table_example (1, 7)

my_table_example
+------------+-----------+----------+
| start_Time | end_time  | duration |
+------------+-----------+----------+
|     1      |     2     |    1     |
|     2      |     5     |    3     |
|     1      |     7     |    6     | 
+------------+-----------+----------+
sql postgresql ddl
1个回答
1
投票

您可以尝试手册...

CREATE TABLE my_table_example (
    start_time timestamp,
    end_time timestamp,
    duration interval GENERATED ALWAYS AS ( end_time - start_time ) STORED
);

INSERT INTO my_table_example(start_time, end_time) 
VALUES ('2023-10-01 23:00', '2023-10-02 14:00') 
RETURNING *;
© www.soinside.com 2019 - 2024. All rights reserved.