你有下一张桌子 -
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 |
+-----+------+