让我说我的SQL数据库中有3个表:
AspNetUserRoles -保留将用户与角色链接的记录 AspNetUsers -保留用户 AspNetRoles -担任角色
我想更新分配给电子邮件为some@email.com的用户的角色
我创建了此查询,它可以正常工作:
-- Update tester account role
Update AspNetUserRoles
Set RoleId = 4
From AspNetUsers as b Inner Join AspNetUserRoles as a
On a.UserId = b.Id Where b.Email = 'some@email.com'
现在,如何编辑此查询,而不是提供 RoleId (在本例中为4),而是通过指定其名称从其表中检索特定的角色ID? AspNetRoles 表的字段为“ name”,我尝试了另一个内部联接,但失败了。任何帮助将不胜感激,谢谢。
答案 0 :(得分:2)
在您的UPDATE
查询中,我删除了JOIN
,因为您的邮件表中有此信息。
所以我添加了子查询来更新您的RoleId
尝试一下:
UPDATE AspNetUserRoles
SET RoleId = (SELECT c.id FROM AspNetRoles c WHERE c.name = 'MyRoleName')
FROM AspNetUsers as b
WHERE b.Email = 'some@email.com'
AND AspNetUserRoles.UserId = b.Id
答案 1 :(得分:1)
您可以编写查询以根据名称获取角色的ID
SELECT r.id
FROM AspNetRoles r
WHERE r.name = 'YourRoleName'
LIMIT 1
并在主目录中将此查询用作子查询:
Update AspNetUserRoles
Set RoleId =
(
SELECT r.id
FROM AspNetRoles r
WHERE r.name = 'YourRoleName'
LIMIT 1
)
From AspNetUsers as b Inner Join AspNetUserRoles as a
On a.UserId = b.Id Where b.Email = 'some@email.com'
答案 2 :(得分:1)
您可以像这样使用JOIN
:
update aur
set RoleId = 4
from AspNetUsers au join
AspNetUserRoles ur
on aur.UserId = au.Id join
AspNetRoles r
on ur.RoleId = r.roleId
where au.Email = 'some@email.com' and
r.Name = ?;
这似乎很奇怪。 ApsNetUserRoles
听起来像一个联结表。我希望您通过在此表中插入角色来添加角色。
答案 3 :(得分:0)
尝试一下:
Update AspNetUserRoles
Set AspNetUserRoles.RoleId = a.RoleId
From AspNetUsers as b
Inner Join AspNetUserRoles as a
On a.UserId = b.Id
Where b.Email = 'some@email.com'
and a.name = 'name'