简体   繁体   English

MySQL多对多:先插入表,然后再插入联结表?

[英]MySQL many-to-many: Insert into table and then into junction table?

I have 3 tables: persons , places and person_place . 我有3个表: personsplacesperson_place

Each person can have many favorite places, just as each place can be "favorited" by many persons/people. 每个人可以有许多喜欢的地方,就像每个人可以被许多人/人“喜爱”一样。

CREATE TABLE persons
(
ID int NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL
//some fields omitted
);

CREATE TABLE places 
(
ID int NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
address VARCHAR(50) NOT NULL
//some fields omitted
);

CREATE TABLE person_place 
(
ID int NOT NULL AUTO_INCREMENT,
personID int NOT NULL, //references persons.id
placeID int NOT NULL //references places.id
)

Let's say a user favorites a new place (by some web page). 假设某个用户(通过某个网页)收藏了一个新地点。

How should I insert the new place and then get it's id in order to add the person_place row? 我应该如何插入新地点,然后获取其ID以添加person_place行?

Thank you. 谢谢。

I would wrap the inserts inside a transaction and then use LAST_INSERT_ID() to get the id of the last inserted item. 我将插入内容包装在事务中,然后使用LAST_INSERT_ID()获取最后插入的项目的ID。

START TRANSACTION;
INSERT INTO places(name,address) VALUES('someplace', '...');
SET @last_inserted_id = LAST_INSERT_ID();

INSERT INTO person_place (personID, placeID) VALUES (1, @last_inserted_id)

COMMIT;

我相信在MySQL中,您将使用LAST_INSERT_ID()函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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