Postgres: come fare le chiavi composite?
-
18-09-2019 - |
Domanda
Non riesco a capire l'errore di sintassi nella creazione di una chiave composita. Può essere un errore logico, perché ho provato molte varietà.
Come si crea chiavi composte in Postgres?
CREATE TABLE tags
(
(question_id, tag_id) NOT NULL,
question_id INTEGER NOT NULL,
tag_id SERIAL NOT NULL,
tag1 VARCHAR(20),
tag2 VARCHAR(20),
tag3 VARCHAR(20),
PRIMARY KEY(question_id, tag_id),
CONSTRAINT no_duplicate_tag UNIQUE (question_id, tag_id)
);
ERROR: syntax error at or near "("
LINE 3: (question_id, tag_id) NOT NULL,
^
Soluzione
Lo specifica PRIMARY KEY
composto già fa ciò che si vuole. Omettere la linea che si sta dando un errore di sintassi, e omettere il CONSTRAINT
ridondante (già implicita), troppo:
CREATE TABLE tags
(
question_id INTEGER NOT NULL,
tag_id SERIAL NOT NULL,
tag1 VARCHAR(20),
tag2 VARCHAR(20),
tag3 VARCHAR(20),
PRIMARY KEY(question_id, tag_id)
);
NOTICE: CREATE TABLE will create implicit sequence "tags_tag_id_seq" for serial column "tags.tag_id"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "tags_pkey" for table "tags"
CREATE TABLE
pg=> \d tags
Table "public.tags"
Column | Type | Modifiers
-------------+-----------------------+-------------------------------------------------------
question_id | integer | not null
tag_id | integer | not null default nextval('tags_tag_id_seq'::regclass)
tag1 | character varying(20) |
tag2 | character varying(20) |
tag3 | character varying(20) |
Indexes:
"tags_pkey" PRIMARY KEY, btree (question_id, tag_id)
Altri suggerimenti
L'errore che si stanno ottenendo è in linea 3. vale a dire che non è in
CONSTRAINT no_duplicate_tag UNIQUE (question_id, tag_id)
, ma in precedenza:
CREATE TABLE tags
(
(question_id, tag_id) NOT NULL,
definizione della tabella corretta è come Pilcrow mostrato.
E se si desidera aggiungere unica sul tag1, tag2, tag3 (che suona molto sospetta), quindi la sintassi è:
CREATE TABLE tags (
question_id INTEGER NOT NULL,
tag_id SERIAL NOT NULL,
tag1 VARCHAR(20),
tag2 VARCHAR(20),
tag3 VARCHAR(20),
PRIMARY KEY(question_id, tag_id),
UNIQUE (tag1, tag2, tag3)
);
o, se si vuole avere il vincolo di nome secondo la tua volontà:
CREATE TABLE tags (
question_id INTEGER NOT NULL,
tag_id SERIAL NOT NULL,
tag1 VARCHAR(20),
tag2 VARCHAR(20),
tag3 VARCHAR(20),
PRIMARY KEY(question_id, tag_id),
CONSTRAINT some_name UNIQUE (tag1, tag2, tag3)
);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow