gpt4 book ai didi

postgresql - 使用基于 View 定义的默认值插入到 postgres View 中

转载 作者:行者123 更新时间:2023-11-29 12:35:18 25 4
gpt4 key购买 nike

你好!假设 vehicle 可以是“car”、“truck”或“motorcycle”类型。每辆车都有一个 top_speed(以 km/h 为单位)和一个 license_plate 字符串。

例如

CREATE TABLE vehicle (
type VARCHAR(20) NOT NULL,
top_speed INTEGER NOT NULL,
license_plate VARCHAR(10) NOT NULL
);

INSERT INTO vehicle (type, top_speed, license_plate)
VALUES
('car', 120, 'abc123'),
('truck', 110, 'def456'),
('motorcycle', 140, 'ghi789');

现在为每种类型的车辆添加 View :

CREATE VIEW car AS (SELECT * FROM vehicle WHERE type='car');
CREATE VIEW truck AS (SELECT * FROM vehicle WHERE type='truck');
CREATE VIEW motorcycle AS (SELECT * FROM vehicle WHERE type='motorcycle');

这一切都很好,花花公子。但是当我尝试插入这些 View 时,我遇到了一个不舒服的情况:

INSERT INTO car (type, top_speed, license_plate)
VALUES
('car', 160, 'v4n1ty');

我的问题是我已经插入到一个名为“car”的 View 中...为什么我还要费心去指定 type = 'car'

如果我从这个插入查询中省略 type 列,我会得到一个错误,指出 type 列不允许包含 NULL。似乎 postgres 不会默认省略值,即使它们可以从 View 的定义中收集。

有没有办法让 postgres 查看 View 的定义,以便为 INSERT 查询中省略的列提供默认值?

最佳答案

有很强大的rule system在 PostgreSQL 中。

除了您的代码:

create rule car_insert as on insert to car do instead
insert into vehicle(type, top_speed, license_plate)
values('car', new.top_speed, new.license_plate);

insert into car(top_speed, license_plate) values(160,'v4n1ty');

table car;
┌──────┬───────────┬───────────────┐
│ type │ top_speed │ license_plate │
├──────┼───────────┼───────────────┤
│ car │ 120 │ abc123 │
│ car │ 160 │ v4n1ty │
└──────┴───────────┴───────────────┘

关于postgresql - 使用基于 View 定义的默认值插入到 postgres View 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50123752/

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