Pregunta

No puedo entender el error de sintaxis en la creación de una clave compuesta. Puede ser un error de lógica, porque he probado muchas variedades.

¿Cómo se crea claves compuestas en 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,
                          ^
¿Fue útil?

Solución

Su especificación PRIMARY KEY compuesto ya hace lo que quiere. Omitir la línea que te está dando un error de sintaxis, y omitir la CONSTRAINT redundante (ya implícita), también:

 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)

Otros consejos

El error que está recibiendo es en la línea 3. decir que no está en

CONSTRAINT no_duplicate_tag UNIQUE (question_id, tag_id)

pero antes:

CREATE TABLE tags
     (
              (question_id, tag_id) NOT NULL,

definición de la tabla correcta es como Pilcrow mostró.

Y si desea agregar único en la etiqueta 1, etiqueta 2, etiqueta 3 (que suena muy sospechoso), la sintaxis es:

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, si se quiere tener la restricción con nombre según su deseo:

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)
);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top