Postgres: How to do Composite keys?

后端 未结 2 1784
一生所求
一生所求 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: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)
    );
    

提交回复
热议问题