Christian Giordano wrote:
There's a SQL function LAST_INSERT_ID().
http://dev.mysql.com/doc/mysql/en/in...functions.html
I've already tried with this, but it returns 0 and I don't know how to
tell it in which table to get the number, so I used "SHOW TABLE STATUS"
and then I look for my data :S
"LAST_INSERT_ID() ...
The last ID that was generated is maintained in the server on a
per-connection basis. This means the value the function returns to a
given client is the most recent AUTO_INCREMENT value generated by that
client."
If you connect to the database and query for LAST_INSERT_ID before you
do any inserts or updates that would cause an id to be generated, then
yes, it would be zero. The function only returns the last id generated
_during your current client session_.
I suspect that if you're trying to get the last insert id without having
inserted anything, you're not using it for its intended purpose. The
intended purpose is to make it easier to insert rows in dependent tables
that reference a row you inserted into your primary table:
INSERT INTO myMasterTable (val1, val2) VALUES (123, 456); /* autoinc
field is not named, thus gets a new incremented value */
INSERT INTO myDependentTable (fKey, val3, val4) VALUES
(LAST_INSERT_ID(), 789, 'abc');
This works because the last insert id is isolated to your current client
connection. Even if someone else is working on the database
concurrently and does their own insert to myMasterTable between the two
inserts you do, you still get the correct results.
But the purpose of LAST_INSERT_ID() is not for querying the greatest
value in an autoincrementing column.
Regards,
Bill K.