我有这种表结构:
CREATE TABLE Users
([UserId] int,
[IdDepartment] int);
INSERT INTO Users
([UserId], [IdDepartment])
VALUES
(1, 5),
(2, 0),
(3, -1),
(4, 0),
(5, -1),
(6, 0);
CREATE TABLE Department
([IdDepartment] int, [Name] varchar(23), [IdUser] int);
INSERT INTO Department
([IdDepartment], [Name], [IdUser])
VALUES
(1, 'Sales', 3),
(2, 'Finance', null ),
(3, 'Accounting' , 5),
(4, 'IT' ,3),
(5, 'Secretary',null),
(6, 'Sport',3);
我想用这个结果查询:在用户表中,如果 IdDepartment 为 0,则表示用户是管理员,因此他可以查看所有部门。如果用户在 idpartment 中有 -1,则意味着用户可以访问有限的部门,所以在这种情况下,我对 Department 表进行内部连接以获取该部门的列表。最后一种情况是,如果用户在用户表中的 idDepartament 有一个不同于 0 和 -1 的编号,则表示该用户只能访问该部门。
我试图做类似的事情,但它的结构不是很好:
select
case idDepartment
when 0 then (select Name from Department)
when -1 then (select Name from Department where IdUser = 3)
else (select Name from Department
inner join Users on Department.idDepartment = Users.Department
where Users.UserId = 3)
end
from
Department
where
IdUser = 3
我怎样才能做到这一点?谢谢。
我为我想要获得的内容添加了一个示例:
-For the user that has the userid (1) --> Department Name --------------- Secretary -For the user that has the userid (2) --> Department Name --------------- Sales Finance Accounting IT Secretary Sport -For the user that has the userid (3) --> Department Name --------------- Sales IT Sports