A bit of a quiz to see if you’re paying attention:
First, we’ll set up a couple tables with some auto increment fields:
CREATE TABLE t1 (id INT AUTO_INCREMENT, INDEX(id)); CREATE TABLE t2 (id INT AUTO_INCREMENT, refT1 INT, INDEX(id));
Next, we’ll insert a row to one table:
INSERT INTO t1 VALUES (NULL);
Then, we’ll see what happens when we insert two rows using LAST_INSERT_ID():
INSERT INTO t2 VALUES (LAST_INSERT_ID(), 1), (LAST_INSERT_ID(), 2);
What happens here? Did the insert go ok, or did we get an error? What happens if we now issue
SELECT * FROM t2;
No errors, because we defined the auto_increment field for t2 not as a primary or unique key, but just with index. Remember that LAST_INSERT_ID() only picks up the last value you inserted using NULL, and not explicitly defined values. So we get two copies of the value ‘1’ in our id field.
+----+-------+ | id | refT1 | +----+-------+ | 1 | 1 | | 1 | 2 | +----+-------+

Leave a Reply