Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Insert with sub-select and multiple rows

I have an existing documents table and a new permissions table. I want to create a script that will give all permissions to all of the existing documents. The documents_permissions table will need the document_id and permission_id (1,2,3). So for each document I will need to insert 3 rows. This is where I am at atm:

INSERT INTO `documents_permissions` (`document_id`, `permission_id`)
SELECT `id`, '1' FROM `documents`

but I'd need to repeat that for each permission. What is the best way to do this?

like image 207
xylar Avatar asked Feb 27 '26 13:02

xylar


1 Answers

try this:

USe CROSS JOIN

INSERT INTO `documents_permissions` (`document_id`, `permission_id`)
select  `id`,a.permissions
 from(
select 1 as permissions union all
select 2 union all
select 3 )a
cross join
`documents` d
like image 146
Joe G Joseph Avatar answered Mar 02 '26 04:03

Joe G Joseph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!