我有一个用户和页面表,并且这两个表之间有多对多的关系,具有桥表用户权限。我想要获取所有页面名称,只有那些被标记为分配给该用户的页面。
想要一些这样的想法
+---------+----------------------------------+
| user_id | page_name | Assigned|
+---------+----------------------------------+
| 1 | Add Project | 0 |
| 1 | Department | 0 |
| 1 | Category | 1 |
| 1 | Item | 0 |
| 1 | Units | 1 |
| 1 | Stock In | 0 |
| 1 | Stock Card Report | 1 |
+---------+------------------------+---------|
现在我的查询就是这个;
Select up.user_id, p.page_name FROM user_privileges up, pages p where p.page_id = up.page_id and up.user_id = 1;
并返回此内容;
+---------+------------------------+
| user_id | page_name |
+---------+------------------------+
| 1 | Add Project |
| 1 | Department |
| 1 | Category |
| 1 | Item |
| 1 | Units |
| 1 | Stock In |
| 1 | Stock Card Report |
+---------+------------------------+
该计划是这样的; 表 - 用户
+---------+-----------+
| user_id | user_name |
+---------+-----------+
| 4 | saif |
| 1 | admin |
| 5 | taqi |
| 2 | rashid |
+---------+-----------+
表格 - 页面
+---------+---------------+
| page_id | page_name |
+---------+---------------+
| 2 | Page 1 |
| 3 | Page 2 |
| 5 | Page 3 |
| 6 | Page 4 |
| 7 | Page 5 |
| 8 | Page 6 |
| 9 | Page 7 |
| 10 | Page 8 |
| 11 | Page 9 |
| 13 | Page 10 |
| 14 | Page 11 |
| 15 | Page 12 |
| 16 | Page 13 |
| 18 | Page 14 |
| 19 | Page 15 |
| 20 | Page 16 |
+---------+---------------+
和user_id的表user_privalges = 1。
+--------------------+---------+---------+
| user_privileges_id | user_id | page_id |
+--------------------+---------+---------+
| 1 | 1 | 2 |
| 2 | 1 | 3 |
| 3 | 1 | 5 |
| 4 | 1 | 6 |
| 5 | 1 | 7 |
| 6 | 1 | 8 |
| 7 | 1 | 9 |
| 8 | 1 | 10 |
| 9 | 1 | 11 |
| 10 | 1 | 13 |
| 11 | 1 | 14 |
| 12 | 1 | 15 |
| 13 | 1 | 16 |
| 14 | 1 | 18 |
| 15 | 1 | 19 |
| 16 | 1 | 20 |
+--------------------+---------+---------+
答案 0 :(得分:1)
Select up.user_id, p.page_name FROM user_privileges up, pages p where p.page_id = up.page_id and up.user_id = 1 AND up.Assigned=1;
"我想要获取所有页面名称,只有那些被标记为分配给该用户的页面。"因此,对于您的编辑,您应该尝试使用case语句
SELECT up.user_id, p.page_name,
CASE
WHEN up.page_id=p.page_id THEN '1'
ELSE '0'
END AS Assigned
FROM pages p left join user_privileges up
ON p.page_id = up.page_id
WHERE up.user_id = 1;
答案 1 :(得分:1)
如果您只是寻找user_id = 1
,那么您可能会做某事
select
1 as user_id,
p.page_name,
case when up.page_id is not null then 1 else 0 end as `Assigned`
from pages p
left join user_privalges up on up.page_id = p.page_id and up.user_id = 1
order by p.page_id