sql - 复合类型的多个插入

标签 sql postgresql types sql-insert

考虑以下模式

CREATE TYPE episode_id AS
(
    season_nr int,
    episode_nr int,
    show_id bigint
);

CREATE TABLE episodes
(
    id episode_id primary key,
    title varchar(255) not null,
    release_date timestamptz null
);

I want to insert to multiple rows in one query;

insert into episodes (id.season_nr, id.episode_nr, id.show_id, title, release_date)
values 
(1, 1, 58811, 'Pilot', null),
(1, 2, 58811, 'Vector', null),
(1, 3, 58811, '274', null),
(1, 4, 58811, 'Single Strand', null),
(1, 5, 58811, 'The White Room', null);

它抛出:

> ERROR: multiple assignments to same column "id" SQL state: 42601

我的客户端库不支持 ROW 语法。我怎样才能做到这一点?

最佳答案

正确的语法:

INSERT INTO episodes (id, title, release_date)
VALUES 
((1, 1, 58811), 'Pilot', null),
((1, 2, 58811), 'Vector', null);

您不能在 INSERT 语句的列列表中引用 id 的单个属性,只能引用整个 列。

添加的括号使三个值成为行类型/复合类型。

关于sql - 复合类型的多个插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22735060/

相关文章:

sql - Rails SQL "select in"跨多个列 : where (code1, code2) in ( ("A", 1), ("A", 3), ("Q", 9))

ruby - 为什么我不能在 Ruby 中递归地附加到数组的末尾?

c# - 声明新类型

mysql - SQL请求以查找是否完全覆盖了一个时间段

sql - 如何在 PostgreSQL 中找到每个类别中的三个最大值?

arrays - 如何循环遍历 JSONb 字段中包含的数组?

ruby-on-rails - PostGIS:如何找到与给定集合最接近的 N 组点?

c++ - 数据类型范围作为节省内存的措施是否重要?

Android SQLite LEFT JOIN - 日期过滤器被忽略

mysql - 在 1 个 mySQL 查询中使用 2 个 INNER JOINS 时出现问题