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

标签 postgresql view

你好!假设 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/

相关文章:

android - 设置 View 的绝对位置

java - 我的 Spring-MVC ContentNegotiatingViewResolver 设置是否正确?如何为不受支持的媒体类型发送 404 错误?

mysql - 从 MySQL View 中的字段中删除部分字符串

postgresql - 分组选择第 n 行 Postgres

mysql - sql通过列号/索引/位置而不是列名选择列

database - 如何获取从 PG::Result 插入的行的 ID

python - psycopg2 忽略多行插入时的重复键冲突

ios - ViewController 通过 ViewController 的 View : I want a drop shadow on the left?

Java Applet - MVC - 如何将模型绑定(bind)到 View ?

postgresql - ServiceStack Ormlite - Postgres 使用 MaxDate 将 Date 属性序列化为 JsonB