[英]MySQL - How to insert into table that has many-to-many relationship
I have a table of persons. 我有一张桌子。 Each person has a property and many persons may have a certain property.
每个人都有财产,许多人可能拥有某些财产。 So this is a many-to-many relationship.
所以这是一个多对多的关系。 This is the schema:
这是架构:
CREATE TABLE persons (
person_id int(11) NOT NULL AUTO_INCREMENT,
firstname varchar(30) NOT NULL,
lastname varchar(30) NOT NULL,
PRIMARY KEY (person_id)
);
CREATE TABLE properties (
property_id int(11) NOT NULL AUTO_INCREMENT,
property varchar(254) NOT NULL UNIQUE,
PRIMARY KEY (property_id)
);
CREATE TABLE has_property (
person_id int(11) NOT NULL,
property_id int(11) NOT NULL,
PRIMARY KEY (person_id,property_id),
FOREIGN KEY (person_id) REFERENCES persons (person_id),
FOREIGN KEY (property_id) REFERENCES properties (property_id)
);
Now lets say i want to insert to the database this person: 现在让我说我想向这个人插入数据库:
persons 人
+-----------+-----------+----------+
| person_id | firstname | lastname |
+-----------+-----------+----------+
| 1 | John | Doe |
+-----------+-----------+----------+
properties 性能
+-------------+------------+
| property_id | property |
+-------------+------------+
| 1 | property_A |
| 2 | property_B |
| 3 | property_C |
+-------------+------------+
has_property has_property
+-----------+-------------+
| person_id | property_id |
+-----------+-------------+
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
+-----------+-------------+
So far the best thing i have thought is to do a regular insert in the persons table: 到目前为止,我想到的最好的事情是在人员表中进行常规插入:
INSERT INTO persons (firstname,lastname) VALUES ('John','Doe');
and then do a select to find the id of the person i just inserted 然后执行选择以查找刚刚插入的人的ID
SELECT person_id FROM persons WHERE firstname='John' AND lastname='Doe';
in order to insert into the other two tables (because i need to know the person_id). 为了插入另外两个表(因为我需要知道person_id)。 But i think there must be a better way, isn't it?
但我认为必须有更好的方法,不是吗?
Here is what i ended up doing. 这就是我最终做的事情。 I hope it helps someone.
我希望它对某人有帮助。
INSERT INTO persons (firstname,lastname) VALUES ('John','Doe');
SET @person_id = LAST_INSERT_ID();
INSERT IGNORE INTO properties (property) VALUES ('property_A');
SET @property_id = LAST_INSERT_ID();
INSERT INTO has_property (person_id,property_id) VALUES(@person_id, @property_id);
INSERT IGNORE INTO properties (property) VALUES ('property_B');
SET @property_id = LAST_INSERT_ID();
INSERT INTO has_property (person_id,property_id) VALUES(@person_id, @property_id);
INSERT IGNORE INTO properties (property) VALUES ('property_C');
SET @property_id = LAST_INSERT_ID();
INSERT INTO has_property (person_id,property_id) VALUES(@person_id, @property_id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.