【问题标题】:SQL: create primary key from foreign key and attributeSQL:从外键和属性创建主键
【发布时间】:2021-03-17 16:23:06
【问题描述】:

我正在尝试从一个外键创建表的主键 并且来自表本身的一个属性。

CREATE TABLE table (
    attribute int,
    FOREIGN KEY (foreign_attribute) REFERENCES foreign_table(foreign_attribute), 
    PRIMARY KEY (attribute, foreign_attribute)
);

这不知何故不起作用,任何人都可以推荐一个替代解决方案并指出上面的错误吗?

P.S.:绝对初学者不要猛击

【问题讨论】:

  • 请问您能解释一下为什么要使用两个字段作为主键。换句话说,为什么您不将列用作 int 和 identity?
  • 无论如何我认为你忘记添加一列然后将其设置为 FOREIGN KEY

标签: mysql sql sqlite foreign-keys create-table


【解决方案1】:

将外键列作为复合主键的一部分是可以的,但在任何情况下,您都需要先创建该列,然后才能添加 FK 约束:

CREATE TABLE table (
    attribute int,
    foreign_attribute int REFERENCES foreign_table(foreign_attribute), 
    PRIMARY KEY (attribute, foreign_attribute)
);

或者如果您想选择 FK 约束的名称:

CREATE TABLE table (
    attribute int,
    foreign_attribute int, 
    PRIMARY KEY (attribute, foreign_attribute),
    CONSTRAINT fk_foreign_table FOREIGN KEY(foreign_attribute) REFERENCES foreign_table(foreign_attribute)
);

子列必须具有与父列相同的数据类型和长度 - 我假设为int。在大多数数据库中,父列在父表中必须是唯一的(或者是主键列)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-09
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多