3

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?

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. So if I wanted to add more permissions would I update it to have select 3 union all select 4 union all ?
You do not need to use UNION ALL unless you have duplicate values like 1,1,2,3,4,4 etc. If you do not have duplicates, UNION keyword is enough
@Bader: UNION ALL is faster than UNION
1
INSERT INTO `documents_permissions` (`document_id`, `permission_id`)
select id, pid from `documents`
cross join (select 1 as pid union select 2 union select 3)X

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.