MySQL多级子查询

时间:2016-02-01 16:38:50

标签: mysql subquery correlated-subquery

我尝试使用连接表中的字段" glpi_items_tickets"进入这样的子查询:

    SELECT
        NAME
    FROM
        (
            SELECT
                NAME
            FROM glpi_computers
            WHERE id = git.items_id
        ) AS t1
    UNION
        (
            SELECT
                NAME
            FROM glpi_monitors
            WHERE   id = git.items_id
        )
    UNION
        (
            SELECT
                NAME
            FROM glpi_networkequipments
            WHERE   id = git.items_id
        )
    UNION
        (
            SELECT
                NAME
            FROM glpi_printers
            WHERE id = git.items_id
        )
) AS aliasIT

但我输入的错误类型为:"#1054 - 未知栏' git.items_id'在where子句"

整个请求:

SELECT
    gt.id,
    (
        SELECT
            NAME
        FROM
            (
                SELECT
                    NAME
                FROM glpi_computers
                WHERE   id = git.items_id
            ) AS t1
        UNION
            (
                SELECT
                    NAME
                FROM glpi_monitors
                WHERE   id = git.items_id
            )
        UNION
            (
                SELECT
                    NAME
                FROM glpi_networkequipments
                WHERE id = git.items_id
            )
        UNION
            (
                SELECT
                    NAME
                FROM glpi_printers
                WHERE id = git.items_id
            )
    ) AS aliasIT
FROM glpi_tickets gt
INNER JOIN glpi_items_tickets git 
ON gt.id = git.tickets_id;

您是否有使用该字段的解决方案" glpi_items_tickets.items_id"进入我的子查询?

2 个答案:

答案 0 :(得分:1)

SELECT ...
FROM
    glpi_tickets gt
    INNER JOIN glpi_items_tickets git 
        ON git.tickets_id = gt.id;
    INNER JOIN
    (
        SELECT NAME, id FROM glpi_computers
        UNION
        SELECT NAME, id FROM glpi_monitors
        UNION
        SELECT NAME, id FROM glpi_networkequipments
        UNION
        SELECT NAME, id FROM glpi_printers
    ) g
        ON g.id = git.items_id

答案 1 :(得分:0)

使用完整的表名而不是别名。

将每个git.items_id替换为glpi_items_tickets.items_id

在编译子查询期间,别名不存在,因为在内部查询被认为有效之前,无法编译外部查询(您设置别名的位置)。