0
INSERT INTO db.a (a,b,c,d,e,f,g,h,i) 
VALUES (2,2,"a",'b','c','d',1,'e',0)

The first insert will insert a new row with a incremental_id. I need to take that incremental_id and make an entry into db.b using that incremental_id, for example, if it was 6005 I would make the following insert.

INSERT INTO db.b 
(a_id, s_id, use_i)
VALUES (6005,7,0)

How can I automatically grab the id of the first insert so my second insert can be built dynamically after the first query?

  • 3
    Use the `LAST_INSERT_ID()` function. – Barmar Jun 25 '19 at 20:28
  • to add to @Barmar 's comment you might need to do `SET @a_id = LAST_INSERT_ID();` after insert into `a` table and use `SET @s_id = LAST_INSERT_ID();` after inserting into a `s` table and use `INSERT INTO db.b (a_id, s_id, use_i) VALUES (@a_id,@s_id,0)` .. As it is not very clear if you have or don't have a `s` table as i saw `s_id` i assumed you also have a `s` table – Raymond Nijland Jun 25 '19 at 20:38

1 Answers1

0

You can use function LAST_INSERT_ID() which will return exactly what you need.

cn007b
  • 16,596
  • 7
  • 59
  • 74