2017-06-29 42 views
0

我工作的PostgreSQL數據庫上,我有一個問題:PostgreSQL的外鍵整數[]是指整數

我想創建一個列categories_ids表申請人(即意味着申請人可以有多個類別),我想創建一個外鍵約束之間的這個列和類別表的列ID。但是pgAdmin的說,這是不可能的:

foreign key constraint "fk_categories_ids" cannot be implemented 
DÉTAIL : Key columns "categories_ids" and "id" are of incompatible types: integer[] and integer. 

編輯1:

CREATE TABLE public.applicants 
(
-- Hérité(e) from table users: id integer NOT NULL DEFAULT nextval('users_id_seq'::regclass), 
-- Hérité(e) from table users: email character(60) NOT NULL, 
-- Hérité(e) from table users: "firstName" character(50) NOT NULL, 
-- Hérité(e) from table users: "lastName" character(50) NOT NULL, 
-- Hérité(e) from table users: password character(50) NOT NULL, 
-- Hérité(e) from table users: role_id integer NOT NULL DEFAULT nextval('users_role_id_seq'::regclass), 
    home boolean NOT NULL, 
    "fullTime" boolean, 
    "partTime" boolean NOT NULL, 
    freelance boolean NOT NULL, 
    internship boolean NOT NULL, 
    "minSalary" integer, 
    domain_id integer, 
    categories_ids integer[], 
    skills_ids integer[], 
    locations_ids integer[], 
    "jobExperiences_ids" integer[], 
    CONSTRAINT pk_applicant_id PRIMARY KEY (id), 
    CONSTRAINT fk_domain_id FOREIGN KEY (domain_id) 
     REFERENCES public.domains (id) MATCH SIMPLE 
     ON UPDATE NO ACTION ON DELETE NO ACTION 
) 
INHERITS (public.users) 
WITH (
    OIDS=FALSE 
); 
+2

這根本不被支持。規範化你的數據模型,然後你可以創建一個合適的外鍵 –

+0

是的,但我不知道如何建模這個配置,我真的剛開始在數據庫上工作,你能告訴我怎麼做? –

+0

您正在尋找關係設計中的「一對多關係」 –

回答

0

刪除categories_ids integer[]場:

create table applicant_category (
    applicant_id int references applicants(id), 
    category_id int references category(category_id), 
    primary key (applicant_id, category_id) 
) 
+0

感謝它工作得很好:) –

+0

這是傳統的方法,EAV。取決於具體情況,情況可能會更糟或更好。 – Nick

0

您不能在陣列列創建FK。不支持。 因此,要麼使用EAV模型(https://en.wikipedia.org/wiki/Entity%E2%80%93attribute%E2%80%93value_model,所以3個表格而不是2),或者沒有外鍵工作(您可以創建自定義觸發器來模擬它們)。

有一些物品使用「非原語」(int[]hstorejsonb)的數據類型進行比較EAV - 例如http://coussej.github.io/2016/01/14/Replacing-EAV-with-JSONB-in-PostgreSQL/https://wiki.hsr.ch/Datenbanken/files/Benchmark_of_KVP_vs.hstore-_doc.pdf有一定的基準。