Shen Siddharta
Shen Siddharta

Reputation: 50

Insert into a table from two different tables

Here I have 3 tables.

let's say the data of each table are:

- sbs_users(table1)
userid    username
1         john
2         albert

- sbs_permissions(table2)
permissionid    permission
1               create
2               edit

- sbs_user_permissions(table3)
upid(autoid)    userid    permissionid

What I wanna do is insert into table3 with the all data from table2 but only get the last id in table1.

So expected after insert is:

- sbs_user_permissions(table3)
upid(autoid)    userid    permissionid
1               2         1
2               2         2

Thanks in advance

Upvotes: 0

Views: 28

Answers (2)

Phil Walton
Phil Walton

Reputation: 963

You probably need something like this...

INSERT INTO sbs_user_permissions (userid, permissionid)

SELECT u.userid, p.permissionid
FROM sbs_users u
INNER JOIN sbs_permissions p ON 1=1
WHERE u.userid = 2;

Upvotes: 0

pala_
pala_

Reputation: 9010

If I read you correctly, you want to give all permissions to the user with the max user id? If so, this:

insert into user_permissions select u.id, p.id from
  users u cross join permissions p
  where u.id = (select max(id) from users);

demo here

Upvotes: 1

Related Questions