有条理地应用SQL WHERE

时间:2014-06-17 17:41:15

标签: sql where

TABLE A
-------
USER ACCESS    RECORD_IDN  
1    ALL       NULL
2    PARTIAL   1
2    PARTIAL   2
3    PARTIAL   5

TABLE B
-------
NAME     FOLDER_ACCESS    R_IDN
FOLDER1  ALL
FOLDER2  ALL
FOLDER3  PARTIAL          5
FOLDER4  PARTIAL          1
FOLDER5  PARTIAL          2
FOLDER5  ALL

当用户1登录时,他没有任何限制我应该显示文件夹1-5。

当用户2登录时,他不应该看到文件夹3(所有和1,2都可以查看)

当用户3登录时,他应该看到FOLDER 1,FOLDER 2,FOLDER3,FOLDER5

问题是我需要有条件地使用WHERE子句:

SELECT DISTINCT NAME * FROM TABLE B   

PSEUDO CODE 

IFF USER_LOGGED IN HAVING 'ALL' in TABLE A 

DO NOTHING 

ELSE IFF ITS PARTIAL 

WHERE FOLDER_ACESS IS "ALL" OR R_IDN in (TABLEA.R_IDN FOR HIM) .

SQL中是否可以构建这样的构造?它更多的是学术上了解什么是可能的,什么是不可能的。我知道通过单独打破它来解决这个问题,但是想知道是否有棘手的解决方案。如果它值得追求单一的棘手解决方案。

目标平台是ORACLE和MSSQL。但是欢迎使用任何SQL平台解决方案。

2 个答案:

答案 0 :(得分:1)

这是你想要实现的目标吗?

SELECT NAME
FROM B 
WHERE EXISTS (
   SELECT *
   FROM A
   WHERE A.USER = @userId 
      AND (A.ACCESS = 'ALL' 
             OR B.FOLDER_ACCESS = 'ALL'
             OR (A.ACCESS = 'PARTIAL' AND A.RECORD_IDN = B.R_IDN)
          )
)
GROUP BY NAME

对于 MS SQL ,可以选择使用CROSS APPLY

SELECT NAME
FROM B 
  CROSS APPLY (
      SELECT 1
      FROM A
      WHERE A.USER = @userId 
      AND (A.ACCESS = 'ALL' 
             OR B.FOLDER_ACCESS = 'ALL'
             OR (A.ACCESS = 'PARTIAL' AND A.RECORD_IDN = B.R_IDN)
          )
)
GROUP BY NAME

答案 1 :(得分:1)

这样做 - 你只需要在where子句中提供你想要结果的用户。例如。对于用户2:

SELECT distinct a.user, b.name
FROM TABLEA a
INNER JOIN TABLEB b ON a.record_idn = b.r_idn 
                    OR a.access = 'ALL' 
                    OR b.folder_access = 'ALL'
WHERE a.user = 2
ORDER BY a.user, b.name