Postgresql如何组织分隔访问

时间:2018-05-18 13:44:52

标签: postgresql

如何正确组织对元素的分隔访问。 我有两个主要表:

CREATE TABLE t_users (
user_id varchar PRIMARY KEY,
user_email varchar
);

CREATE TABLE t_items (
item_id varchar PRIMARY KEY,
owner_id varchar not null references t_users(user_id),
title varchar
);

我正在尝试创建表来区分访问权限:

CREATE TABLE t_access_gropes (
access_group_id varchar PRIMARY KEY,
user_id varchar not null references t_users(user_id)
);

CREATE TABLE t_access_sets (
access_set_id varchar PRIMARY KEY,
item_id varchar not null references t_items(item_id),
access_group_id varchar not null references t_access_gropes(access_group_id)
);

示例数据:

INSERT INTO t_users VALUES ('us123', 'us123@email.com');
INSERT INTO t_users VALUES ('us456', 'us456@email.com');
INSERT INTO t_users VALUES ('us789', 'us789@email.com');

INSERT INTO t_items VALUES ('it123', 'us123', 'title1');
INSERT INTO t_items VALUES ('it456', 'us456', 'title2');
INSERT INTO t_items VALUES ('it678', 'us789', 'title3');
INSERT INTO t_items VALUES ('it323', 'us123', 'title4');
INSERT INTO t_items VALUES ('it764', 'us456', 'title5');
INSERT INTO t_items VALUES ('it826', 'us789', 'title6');
INSERT INTO t_items VALUES ('it568', 'us123', 'title7');
INSERT INTO t_items VALUES ('it038', 'us456', 'title8');
INSERT INTO t_items VALUES ('it728', 'us789', 'title9');


INSERT INTO t_access_gropes VALUES ('ag123', 'us123');
INSERT INTO t_access_gropes VALUES ('ag456', 'us456');
INSERT INTO t_access_gropes VALUES ('ag789', 'us789');


INSERT INTO t_access_sets VALUES ('as123', 'it123', 'ag123');
INSERT INTO t_access_sets VALUES ('as456', 'it456', 'ag123');

最后,我希望区分访问权限。 访问类型: 上市 私人的 给朋友。

我的查询:

select *
from t_items
inner join t_users on t_items.owner_id = t_users.user_id
inner join t_access_gropes on t_users.user_id = t_access_gropes.user_id
inner join t_access_sets on t_items.item_id = t_access_sets.item_id
where t_access_gropes.user_id = 'us123';

有效,但只返回一个值。 谢谢。

1 个答案:

答案 0 :(得分:0)

我认为您希望LEFT OUTER JOIN

上有t_access_sets

SQL Fiddle

查询1

SELECT i.*, 
       u.user_email, 
       g.access_group_id, 
       s.access_set_id 
FROM   t_items i 
       join t_users u 
         ON i.owner_id = u.user_id 
       join t_access_gropes g 
         ON u.user_id = g.user_id 
       left outer join t_access_sets s 
                    ON i.item_id = s.item_id 
WHERE  u.user_id = 'us123'

<强> Results

| item_id | owner_id |  title |      user_email | access_group_id | access_set_id |
|---------|----------|--------|-----------------|-----------------|---------------|
|   it123 |    us123 | title1 | us123@email.com |           ag123 |         as123 |
|   it323 |    us123 | title4 | us123@email.com |           ag123 |        (null) |
|   it568 |    us123 | title7 | us123@email.com |           ag123 |        (null) |