sql - Postgres : How to do Composite keys?

标签 sql postgresql composite-key

我无法理解创建复合键时的语法错误。可能是逻辑错误,因为我测试了很多品种。

如何在 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,
                          ^

最佳答案

您的复合 PRIMARY KEY 规范已经满足了您的要求。省略导致语法错误的行,并省略多余的 CONSTRAINT(已暗示):

 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)

关于sql - Postgres : How to do Composite keys?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1285967/

相关文章:

node.js - pg-promise UTF 连接字符串

mysql - 使用复合键时 rails 出现问题

java - 如何使用 JPA 和 Hibernate 映射复合键?

mysql - 如何使用 Rails 删除 MySQL 中的重复项?

PHP set Hash 与 Swift 应用程序的 Checked hash 不同

mysql - 如何做类似 SELECT "all columns except .."的事情?

mysql - 如何在 MySQL 中运行求值表达式并相应地更新列?

sql - Postgres : join two queries and select based on result

sql - 从函数返回的记录具有连接的列

MySQL - 使一对值唯一