2

I have a table connecting principals to their roles. I have come upon a situation where I need to add a role for each user. I have a statement SELECT id FROM principals which grabs a list of all the principals. What I want to create is something like the following:

INSERT INTO role_principal(principal_id,role_id)
VALUES(SELECT id FROM principals, '1');

so for each principal, it creates a new record with a role_id=1. I have very little SQL experience, so I dont know if I can do this as simply as I would like to or if there is some sort of loop feature in SQL that I could use.

Also, this is for a mySQL db (if that matters)

2
  • Related: stackoverflow.com/questions/1189810/… Commented Jan 13, 2010 at 20:01
  • 2
    Please stop thinking in terms of looping, looping is bad on databases, think interms of affecting sets of data instead. Commented Jan 13, 2010 at 20:18

2 Answers 2

10

Use VALUES keyword if you want to insert values directly. Omit it to use any SELECT (where column count and type matches) to get the values from.

INSERT INTO role_principal(principal_id,role_id)
    (SELECT id, 1 FROM principals);
Sign up to request clarification or add additional context in comments.

2 Comments

When using INSERT . . . SELECT on most SQL systems, you omit the parens around the SELECT statement. I think it's the same in MySQL, but not 100% sure.
I replaced 1 with (SELECT id FROM roles WHERE...) so that it could work for any role. But thank you for guiding me down the right path.
1

To avoid duplicates is useful to add a subquery :

INSERT INTO role_principal(principal_id,role_id) (SELECT id, 1 FROM principals p WHERE NOT EXISTS (SELECT * FROM role_principal rp WHERE rp.principal_id=p.id AND role_id=1) )

1 Comment

Thanks for the additional answer. I know in my specific situation I wont have any duplicates but it is certainly good to know how I would handle that situation.

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.