MySQL - 如何插入具有多对多关系的表中

时间:2013-10-31 18:44:38

标签: mysql many-to-many relationship sql-insert

我有一张人的桌子。每个人都有财产,许多人可能拥有某些财产。所以这是一个多对多的关系。这是架构:

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)
);

现在假设我想向这个人插入数据库:

  • 姓: '约翰'
  • 名字: 'Doe的'
  • 属性: 'property_A', 'property_B', 'property_C'

+-----------+-----------+----------+
| person_id | firstname | lastname |
+-----------+-----------+----------+
|         1 | John      | Doe      |
+-----------+-----------+----------+

属性

+-------------+------------+
| property_id |  property  |
+-------------+------------+
|           1 | property_A |
|           2 | property_B |
|           3 | property_C |
+-------------+------------+

has_property

+-----------+-------------+
| person_id | property_id |
+-----------+-------------+
|         1 |           1 |
|         1 |           2 |
|         1 |           3 |
+-----------+-------------+

到目前为止,我所想到的最好的事情是在人员表中进行常规插入:

INSERT INTO persons (firstname,lastname) VALUES ('John','Doe');

然后执行选择以查找刚插入的人的ID

SELECT person_id FROM persons WHERE firstname='John' AND lastname='Doe';

为了插入另外两个表(因为我需要知道person_id)。 但我认为必须有更好的方法,不是吗?

1 个答案:

答案 0 :(得分:29)

这是我最终做的事情。我希望它有所帮助。

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);