还原CTE(公用表Expressin)

时间:2019-07-07 21:57:15

标签: mysql common-table-expression

我之前曾问过一个问题,但是我对查询的理解太深了,以至于我无法采用该解决方案并将其应用于我的原始查询。因此,我正在再次尝试。

我有一个CTE,我需要将其转换为MySQL 5.6的“常规”查询。对于该项目,我们不会很快升级到MySQL 8或MariaDB 10.x。

查询如下:

        WITH currentUserPermissions (permissionID, action, level) AS (
            SELECT
                p.permissionID,
                p.action,
                CASE WHEN p.level = 1 AND rp.level = 1 THEN 2 ELSE COALESCE(rp.level, 0) END AS level
            FROM user_org_sport op
                JOIN rolePermissions rp ON op.roleID = rp.roleID AND op.orgID = rp.orgID
                JOIN permissions p ON p.permissionID = rp.permissionID
            WHERE op.userProfileID = :userID
                AND op.orgID = :orgID
                AND p.systemFlag = 0
        )

        SELECT action, level
        FROM currentUserPermissions

        UNION

        SELECT p.action, p.level
        FROM permissions p
        WHERE p.systemFlag = -1

        UNION

        SELECT p.action, 0 AS level
        FROM permissions p
            LEFT JOIN currentUserPermissions cup ON cup.action = p.action
        WHERE cup.action IS NULL
            AND p.systemFlag = 0

我不是数据库专家(主题专家),所以我们将不胜感激。由于我缺乏数据库经验,所以无法对查询应用上一个答案。

1 个答案:

答案 0 :(得分:2)

对于每个引用,您都需要复制一次CTE:

SELECT action, level
FROM (
    SELECT
        p.permissionID,
        p.action,
        CASE WHEN p.level = 1 AND rp.level = 1 THEN 2 ELSE COALESCE(rp.level, 0) END AS level
    FROM user_org_sport op
    JOIN rolePermissions rp ON op.roleID = rp.roleID AND op.orgID = rp.orgID
    JOIN permissions p ON p.permissionID = rp.permissionID
    WHERE op.userProfileID = :userID
      AND op.orgID = :orgID
      AND p.systemFlag = 0
) x

UNION

SELECT p.action, p.level
FROM permissions p
WHERE p.systemFlag = -1

UNION

SELECT p.action, 0 AS level
FROM permissions p
LEFT JOIN (
    SELECT
        p.permissionID,
        p.action,
        CASE WHEN p.level = 1 AND rp.level = 1 THEN 2 ELSE COALESCE(rp.level, 0) END AS level
    FROM user_org_sport op
    JOIN rolePermissions rp ON op.roleID = rp.roleID AND op.orgID = rp.orgID
    JOIN permissions p ON p.permissionID = rp.permissionID
    WHERE op.userProfileID = :userID
      AND op.orgID = :orgID
      AND p.systemFlag = 0
) cup ON cup.action = p.action
WHERE cup.action IS NULL
  AND p.systemFlag = 0

当然,MySQL 5.x方式为查询增加了冗余,并且由于CTE可能需要计算两次而不是一次而变得更慢。