MySQL VIEW表

时间:2013-04-24 00:29:40

标签: mysql view

我正在努力如何在MySQL中创建VIEW。 我有5张桌子:

- 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

如何创建包含

等数据的VIEW
user_ID  |  page_ID
--------------------
1        | 1
1        | 2
1        | 3
1        | 4
1        | 5
1        | 6
1        | 7

感谢所有可以提供帮助的人。

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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