简体   繁体   中英

Mysql create one-to-one relation

I have 2 tables

 CREATE TABLE `persons` (
 `id` int(6) NOT NULL AUTO_INCREMENT PRIMARY KEY,
 `name`
) ENGINE=InnoDB DEFAULT CHARSET=utf8; 
CREATE TABLE `person_rank` (
 `id` int(6) NOT NULL,
 `wins` int DEFAULT 0,
 `losts` int DEFAULT 0,
 `rank` int DEFAULT 1000
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

How should I create these tables if I want: when one person id added to persons then the same person will be add automatically into person_rank with rank=1000 wins=0 and losts=0 ?

Create AFTER INSERT trigger on persons

DELIMITER ;;
CREATE TRIGGER `persons_ai` AFTER INSERT ON `persons` FOR EACH ROW
    INSERT INTO `person_rank` (`id`, `wins`, `losts`, `rank`) VALUES (new.id, 0, 0, 1000);;
DELIMITER ;

I would do as MarcB said and just run two inserts.

Along with what MarcB said, create a foreign key from persons_rank.id to persons.id that cascades on delete and on update. This will keep them in sync. If you change the id on persons, it will update persons_rank. If you delete the row in persons, it will delete the row in persons_rank.

Lastly, you will want id as primary key in persons_rank as well, since it is 1 to 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM