0

I need to insert a row to 2 tables with matching ids. When inserting to groups table, the id is auto increased.

I want to insert a new row in 'groups' table, get the id from the inserted row and then use it to insert a new row to the 'users_in_groups' table.

What I have:

INSERT INTO groups (name, owner_id ) VALUES ('groupname1', 'userid1'); INSERT INTO users_in_groups (user_id, group_id) VALUES ('userid1', group_id_from_above); 

I tried

INSERT INTO groups (name, owner_id ) OUTPUT Inserted.id VALUES ('group1', 'user1'); 

But I do not know how to make the 2 'insert' work on 1 query. Is it even possible?

2
  • 1
    Are you using MySQL or SQL Server? The OUTPUT syntax is SQL Server. Commented May 2, 2020 at 12:04
  • I am using MySQL. Is there an alternative to output? Commented May 2, 2020 at 15:12

1 Answer 1

2

In MySQL, you can use LAST_INSERT_ID():

INSERT INTO groups (name, owner_id ) VALUES ('groupname1', 'userid1'); INSERT INTO users_in_groups (user_id, group_id) VALUES ('userid1', LAST_INSERT_ID()); 
Sign up to request clarification or add additional context in comments.

2 Comments

That gets the id of the current table to insert, if I am not mistaken.
@WhiteHatMan: this inserts into users_in_groups the id generated when inserting into groups - which is how I understood your question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.