我的PostgreSQL数据库中有3个表,实现了多对多关系:droit
,role
和role_droit
。请参见附图中的图表。我有这个查询来返回当前结果(也在图像中):
SELECT matrix_view.droit_id,
sum(case when matrix_view.aid = 1 then haspair end) as "role A" ,
sum(case when matrix_view.aid = 2 then haspair end) as "role B" ,
sum(case when matrix_view.aid = 3 then haspair end) as "role C" ,
sum(case when matrix_view.aid = 4 then haspair end) as "role D"
from (
SELECT allRD.aid as aid, allRD.droit_id, max(case when RD.role_id is not null then 1 else 0 end) as HasPair
from (
select distinct a.role_id as aid, b.droit_id as droit_id
from role a cross join droit b
) as allRD
left outer join role_Droit RD
on allRD.aid = RD.role_id and allRD.droit_id = RD.droit_id
group by allRD.droit_id, allRD.aid
order by allRD.aid
) AS matrix_view
group by matrix_view.droit_id
order by matrix_view.droit_id
我想在id_droit
和id_role
的交集中显示haspair
,droit
和role
的串联! 所需结果也位于图片中:
答案 0 :(得分:0)
请注意:您在查询中使用固定数字("role A" , "role B" , "role C" , "role D"
),我也使用它们。
尝试以下查询:
SELECT cast(matrix_view.droit_name as text),
matrix_view.droit_id || ',' || sum(case when matrix_view.aid = 1 then matrix_view.aid end) || ',' || sum(case when matrix_view.aid = 1 then haspair end) as "role A" ,
matrix_view.droit_id || ',' || sum(case when matrix_view.aid = 2 then matrix_view.aid end) || ',' || sum(case when matrix_view.aid = 2 then haspair end) as "role B" ,
matrix_view.droit_id || ',' || sum(case when matrix_view.aid = 3 then matrix_view.aid end) || ',' || sum(case when matrix_view.aid = 3 then haspair end) as "role C" ,
matrix_view.droit_id || ',' || sum(case when matrix_view.aid = 4 then matrix_view.aid end) || ',' || sum(case when matrix_view.aid = 4 then haspair end) as "role D"
from (
SELECT allRD.aid as aid, allRD.droit_id,allRD.droit_name , max(case when RD.role_id is not null then 1 else 0 end) as HasPair
from (
select distinct a.role_id as aid, b.droit_id as droit_id , b.droit_name as droit_name
from role a cross join droit b
) as allRD
left outer join role_Droit RD
on allRD.aid = RD.role_id and allRD.droit_id = RD.droit_id
group by allRD.droit_id, allRD.aid ,allRD.droit_name
order by allRD.aid
) AS matrix_view
group by matrix_view.droit_id, matrix_view.droit_name
order by matrix_view.droit_id
答案 1 :(得分:0)
通常,枢轴/交叉表问题。但是,由于您希望获得一小组给定角色的结果,我们可以采用一种捷径:
SELECT droit_name
, droit_id || ',1,' || EXISTS (SELECT FROM role_droit WHERE droit_id = d.droit_id AND role_id = 1)::int AS "role A"
, droit_id || ',2,' || EXISTS (SELECT FROM role_droit WHERE droit_id = d.droit_id AND role_id = 2)::int AS "role B"
, droit_id || ',3,' || EXISTS (SELECT FROM role_droit WHERE droit_id = d.droit_id AND role_id = 3)::int AS "role C"
, droit_id || ',4,' || EXISTS (SELECT FROM role_droit WHERE droit_id = d.droit_id AND role_id = 4)::int AS "role D"
FROM droit d
ORDER BY droit_id;
准确地产生您想要的结果。
我手动提供了角色名称和ID,因为您只需要给定角色的结果,并且无论如何都无法在SQL中动态更改列的数量和名称。
dbfiddle here