2012-04-09 60 views
0

我需要帮助!例如,有四个表格:汽车,用户,部门和join_user_department。由于某些用户的访问权限有限,因此用户和部门之间的M:N关系使用最后一个表。我需要获取用户有权访问的部门中的汽车数量。表“汽车”有一个列department_id。如果表join_user_department没有任何user_id记录,这意味着他可以访问所有部门,并且选择查询必须没有任何条件。我需要做这样的事情:如果在oracle中选择查询

declare 
DEP_NUM number;--count of departments where user have access 
CARS_COUNT number;--count of cars 
BEGIN 
SELECT COUNT (*) into DEP_NUM from join_user_departments where user_id=?; 
SELECT COUNT(*) into CARS_COUNT FROM cars where 
    IF(num!=0)—it meant that user access is limited 
    THEN department_id IN (select dep_id from join_user_departments where user_id=?); 

回答

2

用户无论访问所有汽车(我假设所有的车都依赖于一个部门,并且用户可以访问所有的部门)或用户具有有限的访问。您可以使用UNION ALL将这两个组合在一起,然后按用户分组进行最终计数。我已经加入了交叉与无限制地访问汽车表的用户将其与所有的汽车联系在一起:

(更新到也算部门)

select user_id, 
    count(distinct department_id) as dept_count, 
    count(distinct car_id) as car_count, 
from (
    select ud.user_id, ud.department_id, c.car_id 
    from user_departments ud 
    join cars c on c.department_id = ud.department_id 
    UNION ALL 
    select u.user_id, v.department_id, v.car_id 
    from user u 
    cross join (
     select d.department_id, c.car_id 
     from department d 
     join cars c on c.department_id = d.department_id 
    ) v 
    where not exists (
     select 1 from user_departments ud 
     where ud.user_id = u.user_id 
    ) 
) 
group by user_id 

一个UNION ALL更有效,一个UNION; UNION会查找落入两个组的记录并丢弃重复项。由于每个用户都落入一个或另一个桶中,UNION ALL应该这样做(在外部查询中执行不同的计数也会排除重复项)。

1

“如果表join_user_department不通过USER_ID 有任何记录,这意味着他可以访问所有部门”

这似乎是非常不好的做法。基本上你使用记录的缺失来模拟记录的存在。很乱。如果有用户无法从任何部门访问汽车,会发生什么情况?也许当前的业务逻辑不允许这样做,但是你有一个“数据模型”,它不允许在不改变应用程序逻辑的情况下实现这样的场景。

+0

好点。数据库中应该有一个标志,明确授予用户完全访问权限。 – 2012-04-09 23:11:14