我在表Sections
中的数据库中存储了包含列(sectionId, sectionTypeId, sectionName
)的部分列表,以及表UserPrivilages
中包含列(userPrivilagesId, userId, sectionTypeId
)的权限。
我想从表格Sections
中选择所有部分,但要sectionTypes
{}保存sectionTypeId
UserPrivilages
。
类似的东西:
userId
如果我使用表格SELECT sectionId, sectionTypeId, sectionName, (true/false) as privilage
FROM Sections
加入此表格,我只会在两个表格中都显示结果,但我希望还有用户不要使用UserPrivilages
privilages`的章节。
如果t have
表中的UserPrivilages
存在于sectionTypeId
表中Sections
,那么此真/假来自UserPrivilages
表,而不是返回true,否则为false
所以结果就是例如
userId
答案 0 :(得分:3)
听起来你想要一个左连接,并且当特权中没有行时,COALESCE
可能会替换一个答案:
SELECT
s.sectionId,
s.sectionTypeId,
s.sectionName,
COALESCE(p.privilage,0) as privilage
FROM
Sections s
left join
Privilages p
on
s.sectionTypeId = p.sectionTypeId and
p.UserId = @User
如果不存在匹配项,则会0
。
或者,可能,重新阅读问题,您没有从p
中选择一列,您只想检查是否存在:
SELECT
s.sectionId,
s.sectionTypeId,
s.sectionName,
CASE WHEN p.userPrivilagesId is NULL THEN 0 ELSE 1 END as privilage
FROM
Sections s
left join
Privilages p
on
s.sectionTypeId = p.sectionTypeId and
p.UserId = @User
(假设userPrivilagesId
中的p
是非空列)。