我正在尝试为具有特定权限enabled
标志的用户执行SQL查询。我知道,我可以这样做:
select u.ID, u.Name,
(select p.Value
from Permissions p
where p.UserID = u.ID AND p.Key = 'CanEdit') as IsPermissionEnabled
from Users u
但这不完全是我需要的,我可以做这样的事情:
select u.ID, u.Name,
((select p.Value
from Permissions p
where p.UserID = u.ID AND p.Key = 'CanEdit') = 'True')
as IsPermissionEnabled
from Users u
它对我不起作用。那么,如何更改我的查询以使其工作?
答案 0 :(得分:2)
当然,您应该加入该表格以获取p.Value
。
然后你可以随心所欲地做到这一点:
SELECT
u.ID,
u.Name,
p.Value as IsPermissionEnabled
FROM Users u
LEFT OUTER JOIN Permissions p
ON p.UserID = u.ID
AND p.Key = 'CanEdit';
答案 1 :(得分:1)
尝试此查询
select u.ID, u.Name, case when p.value>0 then 'True' else '' end
as IsPermissionEnabled
from Users u
left join permission p on p.UserID = u.ID and p.key='CanEdit'
答案 2 :(得分:1)
在SQL Server中,您需要一个明确的case
语句。因此,您可以将查询编写为:
select u.ID, u.Name,
(case when (select p.Value
from Permissions p
where p.UserID = u.ID AND p.Key = 'CanEdit'
) = 'True'
then 1 else 0
end) as IsPermissionEnabled
from Users u;
答案 3 :(得分:0)
带有Case的连接(内部或左侧)可用于使用IsPermissionEnabled返回所需的数据。假设intent是将IsPermissionEnabled视为boolean,case语句可以将其设置为0或1的位值,如下所示。
select u.USERID , u.Username, IsPermissionEnabled = case p.[Key] when 'CanEdit' then 1 else 0 end from [Permissions] p inner join [User] u on u.USERID = p.userid