有四张表TB_SYS_USER、TB_SYS_ORG_USER(用户组织机构表)、TB_SYS_USER_ROLE(用户角色表)、TB_SYS_ROLE。其中在TB_SYS_ORG_USER表里,相同的USER_ID可对应多个ORG_ID;在TB_SYS_USER_ROLE表里,相同的USER_ID可对应多个ORG_ID的ROLE_CODE;在TB_SYS_ROLE表里,一个ROLE_CODE对应一个ROLE_NAME。
如下SQL语句查询出TB_SYS_USER里的所有字段,外加TB_SYS_ORG_USER里的组织ID(多个用逗号隔开)和TB_SYS_USER_ROLE里的ROLE_CODE(须关联TB_SYS_ROLE表,得到对应的ROLE_NAME,多个用逗号隔开),采用先聚合再关联的方法:
SELECT B.* FROM (SELECT A.*,ROWNUM RN FROM (
SELECT U.USER_ID,U.PASSWORD_SOURCE,UR.ROLE_NAME as ROLENAME,OU.ORG_ID FROM
(SELECT USER_ID,PASSWORD_SOURCE,PARENT_USER_ID,IS_ENABLE,USER_GUID,IS_INIT_USER,USER_ADDRESS,OPER_USER,USER_TEL,USER_SEX,ID_CARD,USER_EMAIL,USER_NAME,IS_DELETE,LOGON_WAY,MAC_ADDRESS,UK_PASSWORD
,OPER_TIME,USER_PASSWORD,USER_ROLE_LIST,USER_M_TEL,LAST_LOGIN,UK_ID
from TB_SYS_USER order by USER_ID
)U
LEFT JOIN (select user_id,LISTAGG(org_id,',')WITHIN GROUP(ORDER BY USER_ID) as org_id from TB_SYS_ORG_USER group by user_id) OU ON OU.USER_ID = U.USER_ID
LEFT JOIN
( select r1.user_id,LISTAGG(r.role_name,',')WITHIN GROUP(ORDER BY r1.USER_ID) as role_name from TB_SYS_USER_ROLE r1
LEFT JOIN TB_SYS_ROLE r ON R.ROLE_CODE = r1.ROLE_CODE group by user_id
) UR ON UR.USER_ID = U.USER_ID
GROUP BY U.USER_ID,U.PASSWORD_SOURCE,U.PARENT_USER_ID,U.IS_ENABLE,U.USER_GUID,U.IS_INIT_USER,U.USER_ADDRESS,U.OPER_USER,U.USER_TEL,U.USER_SEX,U.ID_CARD,U.USER_EMAIL,U.USER_NAME,U.IS_DELETE
,U.LOGON_WAY,U.MAC_ADDRESS,U.UK_PASSWORD,U.OPER_TIME,U.USER_PASSWORD,U.USER_ROLE_LIST,U.USER_M_TEL,U.LAST_LOGIN,U.UK_ID,oU.org_id,ur.role_name
)A )B