One-to-one relationships occur when there is exactly one record in the first table that corresponds to exactly one record in the related table.

MySQL does not contains any “ready” options to define the one-to-one relationship, but, if you want to enforce it, you can add a foreign key from one primary key to the other primary key, by doing this, both tables will have the one-to-one relationship automatically.

Example

Here’s an example to define a one-to-one relationship in MySQL.

one-to-one-relationship

STOCK table is used to store the frequent use data like stock_code and stock_name, while STOCK_DETAIL is stored the company detail. Both tables contains the same Stock_Id as primary key. And, in STOCK_DETAIL table, Stock_Id is the primary key and also a foreign key to STOCK table.

Note
Another classic one-to-one example is the user and user profile design.

MySQL Script

This is the SQL statement to create tables and enforce the relationship in MySQL.

DROP TABLE IF EXISTS `mkyong`.`stock`;
CREATE TABLE  `mkyong`.`stock` (
  `STOCK_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `STOCK_CODE` VARCHAR(10) NOT NULL,
  `STOCK_NAME` VARCHAR(20) NOT NULL,
  PRIMARY KEY (`STOCK_ID`) USING BTREE,
  UNIQUE KEY `UNI_STOCK_NAME` (`STOCK_NAME`),
  UNIQUE KEY `UNI_STOCK_CODE` (`STOCK_CODE`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=50 DEFAULT CHARSET=utf8;
 
DROP TABLE IF EXISTS `mkyong`.`stock_detail`;
CREATE TABLE  `mkyong`.`stock_detail` (
 `STOCK_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
 `COMP_NAME` VARCHAR(100) NOT NULL,
 `COMP_DESC` VARCHAR(255) NOT NULL,
 `REMARK` VARCHAR(255) NOT NULL,
 `LISTED_DATE` DATE NOT NULL,
 PRIMARY KEY (`STOCK_ID`) USING BTREE,
 CONSTRAINT `FK_STOCK_ID` FOREIGN KEY (`STOCK_ID`) REFERENCES `stock` (`STOCK_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
Tags :
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

Related Posts

Popular Posts