连接查询的别名

时间:2016-12-07 18:12:01

标签: sql dml

( SELECT Vraboteni.v, Ulogi.p, Zarabotuva.honorar 
  FROM Vraboteni, Ulogi, Zarabotuva 
  WHERE Vraboteni.v = Ulogi.v 
    AND ima_uloga='sporedna' 
    AND Ulogi.p = Zarabotuva.p
) as F
JOIN
(  SELECT Vraboteni.v, Ulogi.p, Zarabotuva.honorar 
   FROM Vraboteni, Ulogi, Zarabotuva 
   WHERE Vraboteni.v = Ulogi.v 
     AND ima_uloga='glavna' 
     AND Ulogi.p = Zarabotuva.p
) as S
ON (F.honorar > S.honorar)

有谁能告诉我上面使用的语法有什么问题?我在多个查询中遇到同样的问题,我不确定我是否完全理解在使用连接时我应该如何分配别名(在尝试将alliases分配给多个嵌套连接时具有相同的问题)

2 个答案:

答案 0 :(得分:0)

您加入的子选择应被视为普通表或视图,因此想象它们是,并且您的select语句如下所示:

SELECT1 as F
JOIN SELECT2 as S ON (F.honorar > S.honorar)

此声明缺少必要部分,如SELECT和FROM子句。

所以修复它,如果你想加入两个选择,你应该将它们封装在另一个选择中,这样你得到:

SELECT
  S.*,
  F.*
FROM
  (SELECT ... ) AS F
  JOIN (SELECT ...) AS S ON (F.honorar > S.honorar)

或者,您可以删除两个子选项,对所有表使用常规连接,最后得到如下查询:

SELECT 
  Vraboteni.v, Ulogi.p, Zarabotuva.honorar 
FROM 
  Vraboteni AS v1
    JOIN Ulogi AS u1 ON v1.v = u1.v
    JOIN Zarabotuva AS z1 ON u1.p = z1.p
  CROSS JOIN Vraboteni AS v2 -- Not sure if you would want/need a condition here
    JOIN Ulogi AS u2 ON v2.v = u2.v
    JOIN Zarabotuva AS z2 ON u2.p = z2.p
WHERE 
  v1.ima_uloga = 'sporedna' -- Not sure if this should be v1, u1 or z1
  AND v2.ima_uloga = 'glavna'
  AND z1.honorar > z2.honorar

答案 1 :(得分:0)

这是你需要做的:

SELECT     *
FROM
         (SELECT Vraboteni.v
              , Ulogi.p
              , Zarabotuva.honorar
          FROM   Vraboteni
              , Ulogi
              , Zarabotuva
          WHERE  Vraboteni.v = Ulogi.v
                AND ima_uloga = 'sporedna'
                AND Ulogi.p = Zarabotuva.p) AS F
         JOIN
            (SELECT Vraboteni.v
                 , Ulogi.p
                 , Zarabotuva.honorar
             FROM   Vraboteni
                 , Ulogi
                 , Zarabotuva
             WHERE  Vraboteni.v = Ulogi.v
                   AND ima_uloga = 'glavna'
                   AND Ulogi.p = Zarabotuva.p) AS S ON F.honorar > S.honorar;