Tuesday, January 23, 2007

Mysql Tip

If you insert a row, and needs it the generated id for subsequent inserts into other tables.. i hope every body would have faced this: Here is the cool and simple example..

CREATE TABLE customers
(custid INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name CHAR(40) UNIQUE);
CREATE TABLE sales
(salesid INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
custid INT UNSIGNED NOT NULL,
prodid INT UNSIGNED NOT NULL);
INSERT INTO customers VALUES (NULL,'Some Company');
SET @custid = LAST_INSERT_ID();
INSERT INTO sales VALUES (NULL,@custid,1234);
...

The value returned by LAST_INSERT_ID() is unique for this connection.

No comments: