我的数据库中有 3 个示例表,如下所示: (一)组织结构图 (2) 用户 (3) 发票
我想使用SQL编写一个具有基于层次结构的动态过滤功能的视图。例如,如果我是用户“Jack”,他是 IT 部门的经理,当我执行视图时,我应该只看到发票 ID 1 和 3,因为发票 ID 1 属于我,发票 ID 3 属于我部门 IT 下的另一名员工“Nicole”。另外,我应该看不到发票 ID 2 和 4,因为这些发票不属于 IT 部门下的用户。
这可以在任何关系数据库中使用 SQL 来实现吗?如果可以,还请提供可以实现的SQL语句。谢谢。
我希望这对你有帮助:
WITH
a AS
(SELECT team FROM user
WHERE user_id=1),
b AS (
SELECT DISTINCT department as team, department as sub_team
FROM org
UNION
SELECT DISTINCT department as team, section as sub_team
FROM org
UNION
SELECT DISTINCT department as team, unit as sub_team
FROM org
UNION
SELECT DISTINCT section as team, section as sub_team
FROM org
UNION
SELECT DISTINCT section as team, unit as sub_team
FROM org
UNION
SELECT DISTINCT unit as team, unit as sub_team
FROM org),
c AS (
SELECT b.sub_team FROM a, b
WHERE a.team=b.team
),
d AS (
SELECT user_id FROM user, c
WHERE user.team=c.sub_team
)
SELECT invoice_id FROM invoice, d
WHERE invoice.user_id = d.user_id;
可能有一种更优雅的解决方案,但这个可行。