简体   繁体   中英

Multiple mysql_insert_id

I have 3 table with structure like this,

employee > id (PK), name

family > family_id (PK), id (employee PK)

father > father_id (PK), family_id (family PK), father_name

I know I can get the last inserted id using mysql_insert_id() or LAST_INSERT_ID , and I wanted to get the ID and insert it to each table like this:

INSERT INTO employee VALUES('', '<value>')
//
//
INSERT INTO family VALUES('', '".mysql_insert_id()."')
// id from employee PK
//
INSERT INTO father VALUES('', '".mysql_insert_id()"', '')
// id from family PK

Am I doing the right thing? If yes, is there any better way to do the exact same thing?

Thank you. :)

Yes, that's the right way to do it (given the caveats about the mysql_ fns). But you've quoted an integer value in the 2nd and 3rd examples - which is a bad idea.

The disadvantage to this approach is that it requires multiple round trips to the database even without server side parsing of prepared statements (send query, retrieve results, send request for insert id, retrieve insert id X 3) which can be a performance bottleneck.

If this is the case, then packaging it up as a Mysql function permits the operation to competed as a single call to the DBMS (using a function rather than a procedure, since the former can return the 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.

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