简体   繁体   English

Postgres 将元素插入到用户定义类型列内的数组

[英]Postgres Insert elements to array inside user defined type column

So I'm trying to insert 3 elements inside an array found inside a user defined type which is a column of a table.所以我试图在用户定义的类型中找到的数组中插入 3 个元素,该类型是表的一列。 This is what I have right now:这就是我现在所拥有的:

INSERT INTO pais(pais)
VALUES (ROW ('Espanya', ARRAY['Barcelona', 'Madrid', 'Sevilla'])::t_pais);

The type looks like this:类型如下所示:

CREATE TYPE t_pais AS
(
    nom_pais VARCHAR(35),
    localitzacions t_localitzacio ARRAY
);

The t_localitzacio type looks like this: t_localitzacio 类型如下所示:

create type t_localitzacio as
(
    nom_localitzacio varchar(35)
);

And the table looks like this:该表如下所示:

CREATE TABLE Pais
(
    id_pais serial PRIMARY KEY,
    pais t_pais
);

And i'm getting the following error:我收到以下错误:

malformed record literal: <<Barcelona>>

Thanks in advance!提前致谢!

In your insert, you declare the array to be of type t_pais , but the table expects an array of t_localitzacio :在您的插入中,您将数组声明为t_pais类型,但该表需要一个t_localitzacio数组:

INSERT INTO pais(pais)
VALUES (ROW ('Espanya', ARRAY['Barcelona', 'Madrid', 'Sevilla'])::t_localitzacio);

But why do you do want to store the cities as an array in the country table in the first place?但是,为什么首先要将城市作为数组存储在国家/地区表中? You will get much better performance by using a standard SQL normalized table design:通过使用标准的 SQL 规范化表设计,您将获得更好的性能:

CREATE TABLE country (
    id SERIAL PRIMARY KEY,
    name VARCHAR(255)
);
CREATE TABLE city (
    id SERIAL PRIMARY KEY,
    country_id INT,
    name VARCHAR(255)
);
INSERT INTO country (id, name) VALUES
(1, 'Espanya');
INSERT INTO city (id, country_id, name) VALUES
(1, 1, 'Barcelona'),
(2, 1, 'Madrid'),
(3, 1, 'Sevilla');

SELECT city.*
FROM country
  LEFT JOIN city ON city.country_id = country.id
WHERE country.name = 'Espanya'

If you simplify the t_pais type like this :如果像这样简化 t_pais 类型:

CREATE TYPE t_pais AS
(
    nom_pais VARCHAR(35),
    localitzacions VARCHAR(35)[]
);

then your insert will work.那么您的插入将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM