简体   繁体   English

PostgreSQL 中是否有可用的多值字段类型?

[英]Is there a multivalued field type available in PostgreSQL?

I want to know if it is possible to store multiple values in a field in PostgreSQL.我想知道是否可以在 PostgreSQL 中的一个字段中存储多个值。

I have a table called Token with the columns id , text and category .我有一个名为Token的表,其中包含列idtextcategory category is a multivalued field. category是一个多值字段。 Is it necessary to create a separate table for it or is there a way to store it in the Token table?是不是需要单独为它创建一个表,或者有没有办法将它存储在Token表中?

There are arrays in PostgreSQL. PostgreSQL中有数组 For example: 例如:

CREATE TABLE "token" (
  "id"       integer PRIMARY KEY,
  "text"     text,
  "category" text[]
);

Now you can insert multiple categories for each row into token : 现在,您可以将每行的多个类别插入到token

INSERT INTO "token" ("id", "text", "category")
VALUES (1, 'some text', ARRAY['cate1', 'cate2']);

You can find the rows like: 您可以找到以下行:

SELECT * FROM "token" WHERE 'cate1' = ANY ("category");

There are several: 有几个:

I know that this question had been asked 10 years ago but since Postgres is evolving there are new types that are optimized and could be used to address this issue我知道 10 年前就有人问过这个问题,但由于 Postgres 不断发展,因此出现了经过优化的新类型,可用于解决此问题

  1. json json
  2. jsonb aka binary json jsonb又名二进制 json

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

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