Postgres: How to do Composite keys?

后端 未结 2 1783
一生所求
一生所求 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)
    
    0 讨论(0)
  • 2020-12-24 05:02

    The error you are getting is in line 3. i.e. it is not in

    CONSTRAINT no_duplicate_tag UNIQUE (question_id, tag_id)
    

    but earlier:

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

    Correct table definition is like pilcrow showed.

    And if you want to add unique on tag1, tag2, tag3 (which sounds very suspicious), then the syntax is:

    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)
    );
    

    or, if you want to have the constraint named according to your wish:

    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)
    );
    
    0 讨论(0)
提交回复
热议问题