2016-02-01 96 views
0

我嘗試使用從連接表「glpi_items_tickets」字段成這樣子查詢:MySQL的多級子查詢

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子句」

將整個request:

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’到我的子查詢?

+0

嘗試沒有聯合子查詢的括號。他們至少不必要。 – Sebas

回答

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 
0

使用全表名稱而不是別名。

git.items_id更換爲glpi_items_tickets.items_id

在編譯子查詢期間,別名不存在,因爲外部查詢(您設置別名的地方)不能編譯,直到內部查詢被認爲是有效的。