Oracle单行子查询返回多个行错误

时间:2011-09-30 11:55:27

标签: sql oracle oracle11g case

我有一个场景。可以使用一个查询来完成吗?

  • 表公司:单一公司信息,CPK为主键,其中一名经理,负责人,人力资源部

  • 表员工:对于每个公司,都有员工(1人或以上可以达到500人),其中包含独特的empID和经理,负责人,人力资源部门

  • 表员工信息(用于使用Web应用程序):他被分配了一个或多个经理,领导,人力资源(或者可以是全部,全部,所有这意味着他可以看到所有内容)

所以:

Company
--------
CPK (PK)
Manager
Lead
HR

Employees 
--------
empID (PK)
CPK (FK)
Manager
Lead
HR

EmployeesInfo
-------------
USER_ID (FK)
Manager
Lead
HR

网络 - >当用户登录时,他应该获得所有公司信息。如果他有权访问该公司或该公司内的任何员工,那么该行被启用,否则其灰色(禁用)如果其“全部”则他可以编辑每条记录

例如: User1分配给Manager1,Lead1和HR1 然后他可以编辑公司的所有记录,其中Manager = Manager1,Lead = Lead1和HR = HR1 还有员工使用Company.CPK = Employee.CPK和Employee.Manager = Manager1和Employee.Lead = Lead1和Employee.HR = HR1

的公司记录

我的查询到现在但是

select t2.MANAGER from Employees t2 where t2.CPK  = t1.CPK

返回多条记录,预计该怎么办?

SELECT  t1.*,
      --All condition
      CASE WHEN (SELECT MANAGER FROM EmployeesInfo WHERE USER_ID=44) = 'All' then 1
           ELSE(
                --Check for Company
                CASE 
                WHEN t1.MANAGER  in (SELECT MANAGER FROM EmployeesInfo WHERE USER_ID=44) then 1
                WHEN t1.LEAD in (SELECT LEAD FROM EmployeesInfo WHERE USER_ID=44) then 1
                WHEN t1.HR  in (SELECT HR FROM EmployeesInfo WHERE USER_ID=44) then 1
           ELSE(
                --Check Employee M,L,HR for that Company 
                CASE
                WHEN (SELECT t2.MANAGER FROM Employees t2 WHERE t2.CPK  = t1.CPK) in 
                       (SELECT MANAGER FROM EmployeesInfo WHERE USER_ID=44) then 1
                WHEN (SELECT t2.LEAD FROM Employees t2 WHERE t2.CPK = t1.CPK ) in 
                       (SELECT LEAD FROM EmployeesInfo WHERE USER_ID=44) then 1
                WHEN (SELECT t2.HR FROM Employees t2 WHERE t2.CPK  = t1.CPK  ) in 
                       (SELECT HR FROM EmployeesInfo WHERE USER_ID=44) then 1
                ELSE 0 END
                )
           END
           )
      END AS Grey_Out 
FROM Company t1 
WHERE  t1.CPK  ='1234'

最后,我应该将所有公司的grey_out字段设置为(1或0),然后我将使用Grey_Out字段来查找是否应该对其进行编辑。

2 个答案:

答案 0 :(得分:2)

为了理解你的桌子设计,我很头疼。

你听说过加入吗?

SELECT DISTINCT c.*, 
       CASE WHEN e.empid IS NOT NULL OR ei.USER_ID IS NOT NULL
            THEN 1
            ELSE 0
       END AS Grey_Out 
FROM Company c
    LEFT OUTER JOIN EmployeesInfo ei
        ON c.MANAGER = ei.MANAGER 
        OR c.LEAD = ei.LEAD
        OR c.HR = ei.HR
    LEFT OUTER JOIN Employees e
        ON e.CPK = c.CPK
        AND (
               e.MANAGER = ei.MANAGER
            OR e.LEAD = ei.LEAD
            OR e.HR = ei.HR
        )
WHERE c.CPK = '1234'
AND ei.USER_ID = 44

答案 1 :(得分:0)

更改

case
    when (select t2.MANAGER from Table2 t2 where t2.CPK  = t1.CPK) in 
      (Select MANAGER from Table3 where USER_ID=44) then 1

case
    when exists
        (select *
        from 
            Table3 t3
            inner join table2 t2 on t2.manager = t3.manager
        where 
            t3.USER_ID=44 and t2.CPK = t1.CPK) then 1