如何让这个复杂的查询运行得更快?

时间:2016-12-01 20:23:58

标签: mysql subquery

此查询需要20-40秒才能运行。如果可能的话,我需要加快速度。

SELECT DISTINCT a.category, a.key 
FROM system_permissions AS a, system_permission_to_role AS b, 
system_user_to_role AS c, system_users AS d 
WHERE 
( 
    ( 
        a.system_permission_id=b.system_permission_id 
        AND (b.system_role_id=c.system_role_id || c.system_role_id = 0) 
        AND a.system_permission_id NOT IN ( 
            SELECT system_permission_id FROM system_permission_exclusions AS f 
            WHERE d.system_user_id=f.system_user_id 
        ) 
        AND c.system_user_id=d.system_user_id 
    ) 
    OR a.system_permission_id IN ( 
        SELECT system_permission_id 
        FROM system_permission_inclusions AS g 
        WHERE d.system_user_id=g.system_user_id 
    ) 
) 
    AND d.ldap_objectguid = '?'; 

这样做的原因是我正在为超出标准定义角色的权限创建排除和包含表,所以首先我需要排除属于该角色但存在于排除表中的那些,然后我需要添加不属于他们角色的那些,但存在于包含表中。

我愿意重新设计表格。

1 个答案:

答案 0 :(得分:1)

这有用吗?

SELECT DISTINCT P.category, P.key 
FROM system_users U
LEFT OUTER JOIN system_permission_inclusions PI ON PI.system_user_id = U.system_user_id
INNER JOIN system_user_to_role UR ON UR.system_user_id = U.system_user_id
INNER JOIN system_permission_to_role PR ON PR.system_role_id = UR.system_role_id
INNER JOIN system_permissions P ON P.system_permission_id = PR.system_permission_id OR P.system_permission_id = PI.system_permission_id
WHERE U.ldap_objectguid = '?'
  AND P.system_permission_id NOT IN (SELECT system_permission_id FROM system_permission_exclusions WHERE system_user_id = U.system_user_id)