如何在 MySQL 中创建也是主键的外键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5575051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 19:26:37  来源:igfitidea点击:

How to create foreign key that is also a primary key in MySQL?

mysqlinheritanceforeign-keysprimary-key

提问by user456584

This should be a fairly straightforward question, but I'm unable to find an easy answer. How do you create a foreign key that is also a primary key in MySQL? Here's my current attempt:

这应该是一个相当简单的问题,但我找不到简单的答案。你如何创建一个外键,它也是 MySQL 中的主键?这是我目前的尝试:

CREATE TABLE Sale(
    sale_id CHAR(40),
    PRIMARY KEY(sale_id),
    discount DOUBLE,
    type VARCHAR(255),
    price DOUBLE,
    );

CREATE TABLE Normal_Sale(
    sale_id CHAR(40),
    PRIMARY KEY(sale_id);
);

CREATE TABLE Special_Sale(
    sale_id CHAR(40),
    PRIMARY KEY(sale_id);
);

What am I missing here?

我在这里缺少什么?

Thanks in advance.

提前致谢。

回答by dgilland

Add FOREIGN KEY (sale_id) REFERENCES Sale(sale_id)to each foreign table:

添加FOREIGN KEY (sale_id) REFERENCES Sale(sale_id)到每个外部表:

CREATE TABLE Sale(
    sale_id CHAR(40),
    PRIMARY KEY(sale_id),
    discount DOUBLE,
    type VARCHAR(255),
    price DOUBLE
) ENGINE=INNODB;

CREATE TABLE Normal_Sale(
    sale_id CHAR(40),
    PRIMARY KEY(sale_id),
    FOREIGN KEY (sale_id) REFERENCES Sale(sale_id)
) ENGINE=INNODB;

CREATE TABLE Special_Sale(
    sale_id CHAR(40),
    PRIMARY KEY(sale_id),
    FOREIGN KEY (sale_id) REFERENCES Sale(sale_id)
) ENGINE=INNODB;

Just make sure your database is InnoDBwhich supports Foreign References.

只要确保您的数据库InnoDB支持外部引用。