mysql从id的相关表中选择行

时间:2014-08-20 01:43:41

标签: mysql

角色表

id | role_name
----------------------
1  | design
2  | lua
3  | admin
4  | super admin
5  | customer service

产品表

id | role | read | write
1  |  1   |  1   |   0
1  |  2   |  1   |   1
1  |  3   |  0   |   0
1  |  4   |  1   |   1

在查询product id = 1

时,希望编写一个sql查询来获取此记录集
  role_name       | read | write
    design          |   1  |  0
    lua             |   1  |  1
    admin           |   0  |  0
    super admin     |   1  |  1
    customer service|   0  |  0

和插入新产品记录时,用户必须在创建记录时定义权限

role_name       | read | write
design          |   0  |  0
lua             |   0  |  0
admin           |   0  |  0
super admin     |   0  |  0
customer service|   0  |  0

更新: 这是我根据建议的答案尝试的陈述

select a.name, b.read_allowed,b.write_allowed
from groups a
inner JOIN department_groups r 
    on  a.id = r.groups_id  AND r.department_id=1234
left JOIN department_groups_rel c 
    on a.id = c.groups_id
left  join access_matrix b 
    on c.access_matirx_id = b.id 
group by a.id;

我从groups表中获取所有角色,但是没有获得为特定部门设置的读写允许属性

2 个答案:

答案 0 :(得分:0)

即使left join中没有条目

,也可以使用product获取角色
select r.role_name, 
       case when p.read is null then 0 else p.read end as read, 
       case when p.write is null then 0 else p.write end as write
from roles r
left join product p on r.id = p.role
                   and p.id = 1

并使用casenulls替换为0

答案 1 :(得分:0)

To get your first preferred result. Try this

SELECT
    roles.role_name, product.read, product.write
FROM
    roles LEFT JOIN product
    ON roles.id = product.role