Postgres: How to do Composite keys?

后端 未结 2 1785
一生所求
一生所求 2020-12-24 04:24

I cannot understand the syntax error in creating a composite key. It may be a logic error, because I have tested many varieties.

How do you create composite

2条回答
  •  甜味超标
    2020-12-24 05:01

    Your compound PRIMARY KEY specification already does what you want. Omit the line that's giving you a syntax error, and omit the redundant CONSTRAINT (already implied), too:

     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)
    

提交回复
热议问题