-->

科技资讯

您的当前位置:首页 > 资讯 > postgresql

postgresql数据库多对多数据库设计与查询,行列互换

2019-04-08 16:48:19  来源:admin 点击:1226

主表1 部门表enum_dep
iddepname
1A部门
1B部门
1C部门
1D部门
主表2 行业表enum_ind
idindname
1A行业
2B行业
3C行业
4D行业
关联表 部门行业表enum_dep_ind
depidindid
11
12
13
21
22
记得创建外键
postgresql
基础查询,链表查询,不多解释

                SELECT c.id,c.depname,c.desc,d.indname,c.status,d.id as indid from enum_dep as c LEFT JOIN (select a.depid,a.indid,b.indname,b.id from enum_dep_ind as a LEFT JOIN enum_ind as b on a.indid = b.id) as d on c.id = d.depid where c.group = 1 order By c.id

结果会出现多个主表1的重复内容

步骤二,把行合并成单行

select h.id,string_agg(h.indname, ',') as names ,string_agg(h.indid::TEXT,',') as indid from (SELECT c.id,c.depname,c.desc,d.indname,c.status,d.id as indid from enum_dep as c LEFT JOIN (select a.depid,a.indid,b.indname,b.id from enum_dep_ind as a LEFT JOIN enum_ind as b on a.indid = b.id) as d on c.id = d.depid where c.group = 1 order By c.id) as h GROUP BY h.id

string_agg('字符串',‘,’)  或者array_agg(‘字符串’)

最终结果,把主表1的所需字段链接上

SELECT j.id,j.status,j.group,j.groupname,w.names,w.indid,j.depname,j.desc from enum_dep as j LEFT JOIN (select h.id,string_agg(h.indname, ',') as names ,string_agg(h.indid::TEXT,',') as indid from (SELECT c.id,c.depname,c.desc,d.indname,c.status,d.id as indid from enum_dep as c LEFT JOIN (select a.depid,a.indid,b.indname,b.id from enum_dep_ind as a LEFT JOIN enum_ind as b on a.indid = b.id) as d on c.id = d.depid where c.group = 1 order By c.id) as h GROUP BY h.id) as w on w.id =j.id where j.group =1


SELECT d.id,d.pid,d.name,d.unit,d.desc,d.status,string_agg(c.indname, ',') as names,string_agg(c.id::TEXT,',') as indid 

from enum_indicator as d LEFT JOIN 

(select a.indicatorid,b.indname,b.id from enum_indu_indi as a LEFT JOIN enum_ind as b on a.industryid = b.id) as c on d.id = c.indicatorid GROUP BY d.id


、、另外一种方法

select a.id,a.username,array_to_string(array(SELECT (SELECT d.rolesname FROM roles_infor as d WHERE d.id=b.rid) FROM user_roles as b WHERE b.uid=a.id),',') as userrole from user_infor as a group by a.id

如果还有分页和排序问题后面直接加就好了  limit等orderby

相关文章更多 >

© 2024版权所有 水水网

电话:171780793