Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complicated/Simple SQL Insert: adding multiple rows

Tags:

sql

mysql

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)

like image 579
UmYeah Avatar asked Jul 05 '26 13:07

UmYeah


1 Answers

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);
like image 71
Peter Lang Avatar answered Jul 08 '26 11:07

Peter Lang



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!