2017-06-24 4 views
0

異なるカテゴリを含むテーブルがあるとします。次に、最初の列内で複数のカテゴリの配列を参照する必要がある別のテーブルがあります。異なるテーブルの行を参照する列のIDの配列

これは何と呼ばれ、これを行うにはどうすればよいですか?

Postgresの方言:)

Category Id | Category Name 
1   | Category 1 
2   | Category 2 

Product Id | Product Name | Categories 
1   | Product 1 | 1,2 

答えて

3

(あなたは8バイトの整数が必要な場合やint8[])それはちょうど、整数配列、int[]と呼ばれています。

create table category (
    id serial primary key, 
    name text not null 
); 

create table product (
    id bigserial primary key, 
    name test not null, 
    category_ids int[] not null 
); 

あなたは、このアプローチを使用しても、select * from product where '{2}'::int[] <@ category_ids;などの検索をスピードアップするためにproduct.category_ids上GINインデックスを追加することができます - しかし、ここでの明らかな欠点は、Postgresは、参照整合性を確保することができませんということです - あなたは外国人を定義することはできませんint[]のキー。

int[]の代わりにjsonbデータ型を使用し、その列にGINインデックスを追加して検索を高速化することもできます。

あなたは(非常に良いと右の願いです)FKSを持つようにしたい場合は、単に伝統的なアプローチ、EAVは、次のとおりです。

create table category (
    id serial primary key, 
    name text not null 
); 

create table product (
    id bigserial primary key, 
    name test not null 
); 

create table product2category (
    product_id int8 not null references product(id), 
    category_id int not null references category(id), 
    primary key (product_id, category_id) 
); 

EAV対int[]の長所と短所を発見する記事の数がありますが(別名「intarray」)またはjsonbに近づくと、ここにその1つがあります:http://coussej.github.io/2016/01/14/Replacing-EAV-with-JSONB-in-PostgreSQL/ - 私はそのトピックをGoogleに推薦し、あなたのケースにとってより良いものを決定するのに役立つことを学びます。

関連する問題