次のテーブルがあります -
CREATE TABLE `USER`(
APID INT(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (APID)
) ENGINE = INNODB AUTO_INCREMENT = 1;
CREATE TABLE HOBBIES(
HID INT(11) NOT NULL AUTO_INCREMENT,
APID INT(11) DEFAULT NULL,
PRIMARY KEY (HID),
CONSTRAINT FK_HOBBIES_USER_APID FOREIGN KEY (APID) REFERENCES `USER` (APID)
ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = INNODB AUTO_INCREMENT = 1;
CREATE TABLE SKILLS(
SID INT(11) NOT NULL AUTO_INCREMENT,
APID INT(11) DEFAULT NULL,
PRIMARY KEY (SID),
CONSTRAINT FK_SKILLS_USER_APID FOREIGN KEY (APID) REFERENCES `USER` (APID)
ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = INNODB AUTO_INCREMENT = 1;
ID プライマリ フィールドは AUTO_INCREMENT として宣言されているため、この機能を使用することをお勧めします - NULL 値を追加すると、MySQL は新しい ID 値 (1、2、3 など) を生成します -
-- Add first user and all his properties (hobbies, skills)
INSERT INTO user(apID) VALUES(NULL); -- We pass NULL
-- But real ID is 1, we set this value to variable @id
-- This @id will be used to insert correct foreign key values in child tables
SET @id = LAST_INSERT_ID();
-- Add some hobbies and skills for user 1
INSERT INTO hobbies(hID, apID) VALUES (NULL, @id);
INSERT INTO hobbies(hID, apID) VALUES (NULL, @id);
INSERT INTO hobbies(hID, apID) VALUES (NULL, @id);
INSERT INTO skills(sID, apID) VALUES (NULL, @id);
INSERT INTO skills(sID, apID) VALUES (NULL, @id);
INSERT INTO skills(sID, apID) VALUES (NULL, @id);
各ユーザーに対して同じことを行います。
チェック結果:
SELECT * FROM `user`;
+------+
| APID |
+------+
| 1 |
+------+
SELECT * FROM hobbies;
+-----+------+
| HID | APID |
+-----+------+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
+-----+------+
SELECT * FROM skills;
+-----+------+
| SID | APID |
+-----+------+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
+-----+------+