Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

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.

like image 983
user456584 Avatar asked Apr 07 '11 01:04

user456584


People also ask

Can a foreign key be a primary key in the same table?

If you mean "can foreign key 'refer' to a primary key in the same table?", the answer is a firm yes as some replied.

Can I have the same field as primary key and foreign key in mysql?

You can create a column having both keys (primary and foreign) but then it will be one to one mapping and add uniqueness to this column.


1 Answers

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.

like image 52
dgilland Avatar answered Sep 28 '22 03:09

dgilland