[英]Insert into a table values as the result of a SQL query
I have three tables Users, Roles and UserRoles. 我有三个表Users,Roles和UserRoles。 Users has a primary key called as Id, Roles has a primary key called Id and UserRoles has two foreign key references to Users and Roles called UserId and RoleId.
用户有一个称为ID的主键,角色有一个称为ID的主键,而UserRoles有两个对用户和角色的外键引用,分别称为UserId和RoleId。
I need to insert into the UserRoles a UserId, RoleId pair as the result of a SQL query on the Users and Roles table. 我需要在UserRoles中插入一个UserId和RoleId对,作为对Users and Roles表的SQL查询的结果。
The queries are something like this: 查询是这样的:
SELECT ID FROM Users WHERE Email = 'something@something.com';
and 和
SELECT ID From Roles WHERE Name = 'Admin';
I need to use them like this: 我需要这样使用它们:
INSERT INTO UserRoles (UserId, RoleId) VALUES (SELECT ID FROM Users WHERE Email = 'something@something.com', SELECT ID From Roles WHERE Name = 'Admin');
How can I do this. 我怎样才能做到这一点。
this should work for you.. 这应该为您工作。
declare @userId int, @roleid int
select @userId = Id FROM Users
select @roleid = Id from Roles
insert into UserRoles (UserId, RoleId) value (@userId,@roleid)
Please consider your where condition into select queries. 请在选择查询时考虑您的条件。
Try this. 尝试这个。
INSERT INTO UserRoles (UserId, RoleId)
SELECT a.ID, b.ID
FROM Users as a,Roles as b
WHERE a.Email='something@something.com'
AND b.Name='Admin';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.