tags:

views:

17

answers:

1

Consider I have two tables, t1 and t2

t1 = (id, name), t2 = (id, fid)

The fid in t2 is a Foreign Key to t1.

Steps to create rows as following.

  1. Insert a row in t1, get the id
  2. Use that id and insert as fid in t2.

My problem is:

Since t1's id is unknow when the transaction is not committed, so how to perform the insertion to t2?

+2  A: 

If id is auto-incremented in table1 then you can do something like this:

INSERT INTO t1 (name) VALUES ('whatever');
INSERT INTO t2 (fid) VALUES (LAST_INSERT_ID());

This comes from the MySQL Reference Manual.

EDIT: How about if I am inserting 3 tables t1, t2, t3 Both t2 and t3 have a fid equal to t1. But when t3 insert the fid, the LAST_INSERT_ID() is belong to t2, not t1.

Then you could do something like this:

INSERT INTO t1 (name) VALUES ('whatever');
SET @id=LAST_INSERT_ID();
INSERT INTO t2 (fid) VALUES (@id);
INSERT INTO t3 (fid) VALUES (@id);
...
KLee1
Indeed, the new id in t1 **is** known. On a concurrent other transaction (and possibly a rollback or commit) there could be a gap in the sequence of id's, which shouldn't matter.
Wrikken
How about if I am inserting 3 tablest1, t2, t3Both t2 and t3 have a fid equal to t1.But when t3 insert the fid, the LAST_INSERT_ID() is belong to t2, not t1.
Yoga
I have edited my post to answer this different question. You just save the value of `LAST_INSERT_ID()` and then retrieve it when you need it.
KLee1
Thanks. I voted you as the correct answer.Last question, do you think it is also safe to use program to handle the last_insert_id?e.g.$db->execute("INSERT INTO t1 (name) VALUES ('whatever')");$id = $db->get_last_insert_id();$db->execute("INSERT INTO t2 (fid) VALUES ('" . $id . "')");$db->execute("INSERT INTO t3 (fid) VALUES ('" . $id . "')");
Yoga
@Yoga That should be fine. They probably have the same semantics.
KLee1