PostgreSQL子查询中带有别名的语法错误

时间:2011-12-08 17:53:28

标签: sql postgresql

我是SQL新手并尝试执行某个查询,其中需要两个子查询。我必须给他们别名,但是当我这样做时说:

ERROR:  syntax error at or near "as"

但我没有看到语法错误。我在这种查询方面遇到了很多麻烦,而且我找不到太多的信息或例子。你能帮助我吗?

Select
    ...
from
    turno,
    (select * from
        (
            select 
                ...
             from 
                accion
            where
                accion.tipo = 4 or accion.tipo = 5
        ) as part1
        union
        (
            select 
                ...
             from 
                accion
            where
                accion.tipo <> 4 and accion.tipo <> 5
        ) as part2
    ) as accion
where 
    ...
;

非常感谢。

2 个答案:

答案 0 :(得分:2)

您有超过必要的查询级别并将它们混合起来。尝试:

SELECT ...
FROM   turno,
      ( 
    SELECT ...
    FROM   accion
    WHERE  accion.tipo = 4 OR accion.tipo = 5

    UNION
    SELECT ...
    FROM   accion
    WHERE  accion.tipo <> 4 AND accion.tipo <> 5
   ) AS accion
WHERE ...

更好:

SELECT ...
FROM   turno
JOIN   (    
    SELECT ...
    FROM   accion
    WHERE  accion.tipo = 4 OR accion.tipo = 5

    UNION
    SELECT ...
    FROM   accion
    WHERE  accion.tipo <> 4 AND accion.tipo <> 5
   ) AS accion ON <join condition>
WHERE ...

更好的是,简化为:

SELECT ...
FROM   turno
JOIN   (    
    SELECT ...
    FROM   accion
    WHERE  accion.tipo  = 4
       OR  accion.tipo  = 5
       OR (accion.tipo <> 4 AND accion.tipo <> 5)
   ) AS accion ON <join condition>
WHERE ...

产生相同的结果,只有更快和更快简单。

条件限定a.tipo IS NULL中的所有行(accion除外)。因此,在这种特殊情况下,您可以进一步简化:

SELECT ...
FROM   turno
JOIN   accion a ON a.tipo IS NOT NULL AND <join condition>
WHERE  ...

但这可能是由于问题过度简化了,对吗?

最后一个示例还演示了关键字AS在此上下文中仅仅是噪音的方式。

答案 1 :(得分:1)

尝试:

Select
    ...
from
    turno,
    (select * from
        (
            select 
                ...
             from 
                accion
            where
                accion.tipo = 4 or accion.tipo = 5
         union
            select 
                ...
             from 
                accion
            where
                accion.tipo <> 4 and accion.tipo <> 5
        ) as part1_2
    ) as accion
where 
    ...
;