2013-04-24 70 views
0

我正在努力如何在MySQL中創建VIEW。 我有5個表:MySQL查看錶

 
- users - table with users data 
- groups - table with groups data 
- group_membership - relational table storing users memberships in groups 
- pages - table storing all pages data 
- permissions - relational table between pages and groups storing permissions to view page by group. 

,我想創建應該告訴我哪些頁面是允許用戶根據他的小組成員看到的視圖。 例子:

 
User ID 1, is in groups 1, 2, 3 
group 1 has permission for pages 1,2,3 
group 2 has permission for pages 1,2,3,4 
group 3 has permission for pages 1,2,3,4,5,6,7 

如何創建視圖,將包含類似

 
user_ID | page_ID 
-------------------- 
1  | 1 
1  | 2 
1  | 3 
1  | 4 
1  | 5 
1  | 6 
1  | 7 

謝謝大家誰可以幫助數據。

回答

0

這會做你想做的。

CREATE OR REPLACE VIEW `user_permissions` AS 
SELECT DISTINCT `gm`.`user_ID`, `p`.`page_ID` 
FROM `group_memberships` AS `gm` 
INNER JOIN `permissions` AS `p` ON `gm`.`group_ID` = `p`.`group_ID`; 

但是,在這個過程中您將失去索引,並且您的表現將低於標準。

可能更好地做到這一點作爲一個存儲過程,或者只是一個簡單的查詢,如:

SELECT DISTINCT `p`.`page_ID` 
FROM `group_memberships` AS `gm` 
INNER JOIN `permissions` AS `p` ON `gm`.`group_ID` = `p`.`group_ID`; 
WHERE `gm`.`user_ID` = 123; 
+0

你實際上不需要加入到用戶爲此,你可以把gm.user_id – 2013-04-24 00:41:24

+0

作品完美。非常感謝 – 2013-04-28 00:58:14

0

像這樣的東西應該工作:

CREATE OR REPLACE VIEW `user_permission_view` AS 
SELECT g.user_ID, p.page_ID 
FROM group_membership g 
JOIN permissions p ON p.group_ID = g.group_ID 
GROUP BY g.user_ID, p.page_ID 
+0

不需要組 – 2013-04-24 00:43:37

+0

@StevenMoseley如果沒有GROUP BY,您將根據用戶的示例獲得具有相同用戶/頁面對的多行,表明組可以在頁面上重疊。 – gview 2013-04-24 00:45:31