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

前端 未结 1 1227
-上瘾入骨i
-上瘾入骨i 2020-12-28 14:36

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 c

相关标签:
1条回答
  • 2020-12-28 14:46

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

    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 InnoDB which supports Foreign References.

    0 讨论(0)
提交回复
热议问题