I have 3 tables: persons
, places
and person_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?
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.
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()函数。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.