SELECT SD_ID, SD_HOST, D_NAME, MS_CFG_USE_GL FROM 
( SELECT DISTINCT CP_OBJECTID FROM 
  ( SELECT GP_MODULEID AS CP_MODULEID, GP_PERMISSIONID AS CP_PERMISSIONID, GC_OBJECTTYPE AS CP_OBJECTTYPE, GC_OBJECTID AS CP_OBJECTID 
    FROM GROUPCUSTOMERS, GROUPPERMISSIONS WHERE GC_CUSTOMERID=1 AND GC_GROUPID = GP_GROUPID AND GP_MODULEID=2 AND GP_PERMISSIONID=7 AND GC_OBJECTTYPE=1 
    UNION 
    SELECT CP_MODULEID, CP_PERMISSIONID, CP_OBJECTTYPE, CP_OBJECTID FROM CUSTOMERPERMISSIONS WHERE CP_CUSTOMERID=1 AND CP_MODULEID=2 AND CP_PERMISSIONID=7 AND CP_OBJECTTYPE=1 
  ) CP, 
  ( SELECT GP_MODULEID AS UP_MODULEID, GP_PERMISSIONID AS UP_PERMISSIONID, GU_OBJECTTYPE AS UP_OBJECTTYPE, GU_OBJECTID AS UP_OBJECTID 
    FROM GROUPUSERS, GROUPPERMISSIONS WHERE GU_USERID=2 AND GU_GROUPID=GP_GROUPID AND ((GP_MODULEID=0 AND GP_PERMISSIONID=0) OR (GP_MODULEID=2 AND GP_PERMISSIONID=7 AND GU_OBJECTTYPE=1)) 
    UNION 
    SELECT UP_MODULEID, UP_PERMISSIONID, UP_OBJECTTYPE, UP_OBJECTID FROM USERPERMISSIONS WHERE UP_USERID=1 AND ((UP_MODULEID=0 AND UP_PERMISSIONID=0) OR (UP_MODULEID=2 AND UP_PERMISSIONID=7 AND UP_OBJECTTYPE=1)) 
  ) UP 
  WHERE (CP_MODULEID = UP_MODULEID AND CP_PERMISSIONID = UP_PERMISSIONID AND CP_OBJECTTYPE = UP_OBJECTTYPE AND CP_OBJECTID=UP_OBJECTID) 
     OR (UP_MODULEID=0 AND UP_PERMISSIONID=0) 
) PERM, (HOSTINGCONTRACTS LEFT JOIN HOSTINGPLANS ON (HC_PLANID=HP_ID)), SUBDOMAINS, DOMAINS, MAILSERVERS 
WHERE PERM.CP_OBJECTID = HC_ID AND HC_ID=3 AND HC_DELETED=0 AND HC_ID=D_CONTRACTID AND D_ID=SD_DOMAINID AND SD_MAILSERVERID IS NOT NULL 
AND SD_MAILSERVERID = MS_ID AND MS_MANAGED=1 
ORDER BY D_NAME, SD_HOST;

