每个派生表必须拥有它自己的别名 - *每个*派生表或仅在每个查询中?

时间:2015-03-23 02:31:25

标签: mysql

我在这里有这个问题:

SELECT * FROM 
  (SELECT DISTINCT C1.ToLoc, (SELECT ME1.EquipmentNumber FROM MajorEquipment ME1 WHERE C1.ToLoc = ME1.MEId) AS EquipmentNumber FROM MajorEquipment ME1 
  INNER JOIN CableId C1 ON C.FromLoc = ME1.MEId
  WHERE C1.FromLoc = (SELECT ME1.MEId FROM MajorEquipment ME1 WHERE ME1.EquipmentNumber = 'Equipment'))
UNION
  (SELECT DISTINCT C2.FromLoc, (SELECT ME2.EquipmentNumber FROM MajorEquipment ME2 WHERE C2.FromLoc = ME2.MEId) AS EquipmentNumber FROM MajorEquipment ME2 
  INNER JOIN CableId C2 ON C.FromLoc = ME2.MEId
  WHERE C2.ToLoc = (SELECT ME2.MEId FROM MajorEquipment ME2 WHERE ME2.EquipmentNumber = 'Equipment'));

如您所见,我已将每个查询中引用的表格指定为C1C2,以及ME1ME2,但我还是得到错误:

  

每个派生表必须拥有它自己的别名

是否建议我需要每个引用的唯一别名?

2 个答案:

答案 0 :(得分:0)

这是您的查询格式,所以(至少)我可以阅读它:

SELECT *
FROM (SELECT DISTINCT C1.ToLoc,
             (SELECT ME1.EquipmentNumber FROM MajorEquipment ME1 WHERE C1.ToLoc = ME1.MEId) AS EquipmentNumber
      FROM MajorEquipment ME1 INNER JOIN
           CableId C1
           ON C.FromLoc = ME1.MEId
      WHERE C1.FromLoc = (SELECT ME1.MEId FROM MajorEquipment ME1 WHERE ME1.EquipmentNumber = '613-MCC-050')
     ) UNION
     (SELECT DISTINCT C2.FromLoc,
             (SELECT ME2.EquipmentNumber FROM MajorEquipment ME2 WHERE C2.FromLoc = ME2.MEId) AS EquipmentNumber
      FROM MajorEquipment ME2 INNER JOIN
           CableId C2
           ON C.FromLoc = ME2.MEId
      WHERE C2.ToLoc = (SELECT ME2.MEId FROM MajorEquipment ME2 WHERE ME2.EquipmentNumber = '613-MCC-050')
     );
------^

箭头突出显示缺少别名的位置。接下来,我不认为MySQL会接受这个,因为union子查询应该都是括号中的单个查询。你可能需要这个:

SELECT *
FROM ((SELECT DISTINCT C1.ToLoc,
              (SELECT ME1.EquipmentNumber FROM MajorEquipment ME1 WHERE C1.ToLoc = ME1.MEId) AS EquipmentNumber
       FROM MajorEquipment ME1 INNER JOIN
            CableId C1
            ON C.FromLoc = ME1.MEId
       WHERE C1.FromLoc = (SELECT ME1.MEId FROM MajorEquipment ME1 WHERE ME1.EquipmentNumber = '613-MCC-050')
      ) UNION
      (SELECT DISTINCT C2.FromLoc,
              (SELECT ME2.EquipmentNumber FROM MajorEquipment ME2 WHERE C2.FromLoc = ME2.MEId) AS EquipmentNumber
       FROM MajorEquipment ME2 INNER JOIN
            CableId C2
            ON C.FromLoc = ME2.MEId
       WHERE C2.ToLoc = (SELECT ME2.MEId FROM MajorEquipment ME2 WHERE ME2.EquipmentNumber = '613-MCC-050')
      )
     ) t;

(老实说,我总是以这种方式编写查询,所以我可以想象不需要额外的括号。)

此外,select distinct是不必要的。 union无论如何都会删除重复项。

您还可以通过删除开头的SELECT * FROM来修复原始查询。

答案 1 :(得分:0)

每次在()之间进行查询时,如果在另一个SELECT中使用结果,则需要提供别名。

所以在WHERE c1.FromLoc =(...)中你不需要别名。

在SELECT * FROM(...)中你需要一个别名(所以SELECT * FROM(...)some_alias)