问题
I have 2 tables, a Users
table and a User_permissions
table. A user can have many permissions and each permission can be assigned to many different users, although this relationship has not been configured into the database (not my decision!).
Let's say 2 new permissions are created - an admin
permission and a superadmin
permission. Furthermore, every user in the Users
table need to be given this permission by inserting the username and permission name into the User_permissions
table.
Obviously this could be done manually by INSERT INTO User_permissions VALUES (userA, admin)
and so on but given that I have a list of over 1,000 users, is there an easier way of doing this? I was thinking of writing a quick script in Java, but is there an easier way using only SQL?
回答1:
Use insert . . . select
:
INSERT INTO User_permissions(user, permission)
SELECT user, 'admin'
FROM users u;
来源:https://stackoverflow.com/questions/28970599/insert-values-into-table-b-based-on-column-from-table-a