Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql: Inserting values for each row returned by a select

Tags:

sql

postgresql

Hi I'm having trouble trying to figure out how to build the following query:

INSERT INTO role_permissions (role_id, permission)
VALUES (
   (SELECT role_id
    FROM role_permissions
    WHERE permission = 'manage_admins'),
   'create_admins');

INSERT INTO role_permissions (role_id, permission)
VALUES (
   (SELECT role_id
    FROM role_permissions
    WHERE permission = 'manage_admins'),
   'edit_admins');

So basically some context, there is a permission called manage_admins that would allow users to edit/create, but now I need to separate this permission into 2 different permissions. The thing is I also have a role_permissions table where I store all of a role's permissions.

So I need to insert the 2 new permissions for every role that had the old permission, the example I provided is failing because the SELECT query is returning multiple values. So this is what I'm having trouble with, so any help would be greatly appreciated.

like image 575
Tuco Avatar asked Dec 13 '22 18:12

Tuco


2 Answers

Get rid of values:

INSERT INTO role_permissions (role_id, permission)
SELECT rp.role_id, t.permission
FROM role_permissions rp
  cross join (values ('edit_admins'), ('create_admins')) as t(permission)
WHERE rp.permission = 'manage_admins';

The cross join will create two rows with the same role_id and the select will then insert those IDs together with the new permission name into the table.

like image 70
a_horse_with_no_name Avatar answered Dec 17 '22 23:12

a_horse_with_no_name


To insert multiple rows, just omit VALUES:

INSERT INTO role_permissions (...)
SELECT ...
like image 38
Laurenz Albe Avatar answered Dec 18 '22 00:12

Laurenz Albe