[Solved] MySQL Query with Sub-Query optimisation

EverSQL Database Performance Knowledge Base

MySQL Query with Sub-Query optimisation

Database type:

I have built a CMS system with a fairly typical user/group/permission system where users can be members of groups, and permissions can be applied to either the user directly, or to groups which users can be members of.

Permissions can also be 'wildcard' (e.g. apply to all objects) or apply to specific objects designated by a module name and a row id. Permissions can with be 'Allow' which grants access, or 'Deny' which specifically prevents access and overrides any 'Allow' permissions they have been granted elsewhere. Deny is stored in the userpermission/grouppermission table by creating an row with the 'allow' column set to 0.

The following query is currently used (and works) to list all users which have been granted a specific 'wildcard' permission (permissionid 123).

    SELECT
        `user`.*
    FROM
        (
            SELECT
                `user`.*,
                `userpermission`.`allow` AS `user_allow`,
                `userpermission`.`permissionid` AS `user_permissionid`,
                `grouppermission`.`allow` AS `group_allow`,
                `grouppermission`.`permissionid` AS `group_permissionid`

            FROM
                `user`

                LEFT JOIN `userpermission` ON
                    `user`.`userid` = `userpermission`.`userid`
                    AND `userpermission`.`module` = '*'
                    AND `userpermission`.`rowid` = '*'
                    AND `userpermission`.`permissionid` = 18

                LEFT JOIN `usergroup` ON 
                  `user`.`userid` = `usergroup`.`userid`

                LEFT JOIN `grouppermission` ON
                    `usergroup`.`groupid` = `grouppermission`.`groupid`
                    AND `grouppermission`.`module` = '*'
                    AND `grouppermission`.`rowid` = '*'
                    AND `grouppermission`.`permissionid` = 18

                WHERE
                    (
                        `grouppermission`.`allow` = 1
                        OR
                        `userpermission`.`allow` = 1
                    )

        ) AS `user` 

        LEFT JOIN `userpermission` ON
            `user`.`userid` = `userpermission`.`userid`
            AND `userpermission`.`permissionid` = `user`.`user_permissionid`
            AND `userpermission`.`allow` = 0
            AND `userpermission`.`module` = '*'
            AND `userpermission`.`rowid` = '*'

        LEFT JOIN `usergroup` ON 
          `user`.`userid` = `usergroup`.`userid`

        LEFT JOIN `grouppermission` ON
            `usergroup`.`groupid` = `grouppermission`.`groupid`
            AND `grouppermission`.`permissionid` = `user`.`group_permissionid`
            AND `grouppermission`.`allow` = 0
            AND `grouppermission`.`module` = '*'
            AND `grouppermission`.`rowid` = '*'

      GROUP BY `user`.`userid`

      HAVING
        COUNT(`userpermission`.`userpermissionid`) + COUNT(`grouppermission`.`grouppermissionid`) = 0

However it is very slow (~0.5 seconds, with ~3000 users, ~250 groups, ~10000 usergroup joins, ~30 permissions, ~150 grouppermissions and ~30 userpermissions).

permissionid as per the example above is just one permision. It may also be necessary to check multiple permissions e.g. IN(18,19,20) instead of = 18

Explain provides the following output - I think I've got the right columns indexed however I'm not sure about how (or if its possible) to index the derived table:

+----+-------------+-----------------+------+----------------------------+--------------+---------+--------------------------------+------+---------------------------------+
| id | select_type | table           | type | possible_keys              | key          | key_len | ref                            | rows | Extra                           |
+----+-------------+-----------------+------+----------------------------+--------------+---------+--------------------------------+------+---------------------------------+
|  1 | PRIMARY     | [derived2]      | ALL  | NULL                       | NULL         | NULL    | NULL                           |   62 | Using temporary; Using filesort |
|  1 | PRIMARY     | userpermission  | ref  | USERID,PERMISSIONID,ALLOW  | USERID       | 4       | user.userid                    |    2 |                                 |
|  1 | PRIMARY     | usergroup       | ref  | USERID                     | USERID       | 4       | user.userid                    |    4 |                                 |
|  1 | PRIMARY     | grouppermission | ref  | GROUPID,PERMISSIONID,ALLOW | PERMISSIONID | 4       | user.group_permissionid        |    3 |                                 |
|  2 | DERIVED     | user            | ALL  | NULL                       | NULL         | NULL    | NULL                           | 2985 |                                 |
|  2 | DERIVED     | userpermission  | ref  | USERID,PERMISSIONID        | PERMISSIONID | 4       |                                |    1 |                                 |
|  2 | DERIVED     | usergroup       | ref  | USERID                     | USERID       | 4       | [database].user.userid         |    4 |                                 |
|  2 | DERIVED     | grouppermission | ref  | GROUPID,PERMISSIONID       | PERMISSIONID | 4       |                                |    3 | Using where                     |
+----+-------------+-----------------+------+----------------------------+--------------+---------+--------------------------------+------+---------------------------------+

Is it possible to re-write the query without the sub-query so that it can be optimised, or optimise it as-is?

If the data structure needs changing that isn't a huge issue.

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Avoid Selecting Unnecessary Columns (query line: 2): Avoid selecting all columns with the '*' wildcard, unless you intend to use them all. Selecting redundant columns may result in unnecessary performance degradation.
  2. Avoid Selecting Unnecessary Columns (query line: 5): Avoid selecting all columns with the '*' wildcard, unless you intend to use them all. Selecting redundant columns may result in unnecessary performance degradation.
  3. Avoid Subqueries (query line: 4): We advise against using subqueries as they are not optimized well by the optimizer. Therefore, it's recommended to join a newly created temporary table that holds the data, which also includes the relevant search index.
  4. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
  5. Explicitly ORDER BY After GROUP BY (modified query below): By default, the database sorts all 'GROUP BY col1, col2, ...' queries as if you specified 'ORDER BY col1, col2, ...' in the query as well. If a query includes a GROUP BY clause but you want to avoid the overhead of sorting the result, you can suppress sorting by specifying 'ORDER BY NULL'.
Optimal indexes for this query:
ALTER TABLE `grouppermission` ADD INDEX `grouppermission_idx_allow_module_rowid_groupid` (`allow`,`module`,`rowid`,`groupid`);
ALTER TABLE `grouppermission` ADD INDEX `grouppermission_idx_module_rowid_permiss_groupid` (`module`,`rowid`,`permissionid`,`groupid`);
ALTER TABLE `usergroup` ADD INDEX `usergroup_idx_userid` (`userid`);
ALTER TABLE `userpermission` ADD INDEX `userpermission_idx_allow_module_rowid` (`allow`,`module`,`rowid`);
ALTER TABLE `userpermission` ADD INDEX `userpermission_idx_module_rowid_permiss_userid` (`module`,`rowid`,`permissionid`,`userid`);
The optimized query:
SELECT
        `user`.* 
    FROM
        (SELECT
            `user`.*,
            `userpermission`.`allow` AS `user_allow`,
            `userpermission`.`permissionid` AS `user_permissionid`,
            `grouppermission`.`allow` AS `group_allow`,
            `grouppermission`.`permissionid` AS `group_permissionid` 
        FROM
            `user` 
        LEFT JOIN
            `userpermission` 
                ON `user`.`userid` = `userpermission`.`userid` 
                AND `userpermission`.`module` = '*' 
                AND `userpermission`.`rowid` = '*' 
                AND `userpermission`.`permissionid` = 18 
        LEFT JOIN
            `usergroup` 
                ON `user`.`userid` = `usergroup`.`userid` 
        LEFT JOIN
            `grouppermission` 
                ON `usergroup`.`groupid` = `grouppermission`.`groupid` 
                AND `grouppermission`.`module` = '*' 
                AND `grouppermission`.`rowid` = '*' 
                AND `grouppermission`.`permissionid` = 18 
        WHERE
            (
                `grouppermission`.`allow` = 1 
                OR `userpermission`.`allow` = 1
            )) AS `user` 
    LEFT JOIN
        `userpermission` 
            ON `user`.`userid` = `userpermission`.`userid` 
            AND `userpermission`.`permissionid` = `user`.`user_permissionid` 
            AND `userpermission`.`allow` = 0 
            AND `userpermission`.`module` = '*' 
            AND `userpermission`.`rowid` = '*' 
    LEFT JOIN
        `usergroup` 
            ON `user`.`userid` = `usergroup`.`userid` 
    LEFT JOIN
        `grouppermission` 
            ON `usergroup`.`groupid` = `grouppermission`.`groupid` 
            AND `grouppermission`.`permissionid` = `user`.`group_permissionid` 
            AND `grouppermission`.`allow` = 0 
            AND `grouppermission`.`module` = '*' 
            AND `grouppermission`.`rowid` = '*' 
    GROUP BY
        `user`.`userid` 
    HAVING
        COUNT(`userpermission`.`userpermissionid`) + COUNT(`grouppermission`.`grouppermissionid`) = 0 
    ORDER BY
        NULL

Related Articles



* original question posted on StackOverflow here.