在Postgresql的where子句中使用Alias列

时间:2010-07-13 20:41:29

标签: sql postgresql alias

我有这样的查询:

SELECT
    jobs.*, 
    (
        CASE
            WHEN lead_informations.state IS NOT NULL THEN lead_informations.state
            ELSE 'NEW'
        END
    ) AS lead_state
FROM
    jobs
    LEFT JOIN lead_informations ON
        lead_informations.job_id = jobs.id
        AND
        lead_informations.mechanic_id = 3
WHERE
    lead_state = 'NEW'

出现以下错误:

PGError: ERROR:  column "lead_state" does not exist
LINE 1: ...s.id AND lead_informations.mechanic_id = 3 WHERE (lead_state...

在MySql中这是有效的,但显然不在Postgresql中。根据我的收集,原因是查询的SELECT部分的评估晚于WHERE部分。这个问题有一个共同的解决方法吗?

6 个答案:

答案 0 :(得分:58)

我在同一个问题上挣扎,“mysql语法是非标准的”在我看来并不是一个有效的论据。 PostgreSQL还添加了方便的非标准扩展,例如“INSERT ... RETURNING ...”以在插入后获得自动ID。此外,重复大型查询并不是一个优雅的解决方案。

但是,我发现WITH statement非常有帮助。它会在查询中创建一个临时视图,您可以像通常的表一样使用它。我不确定我是否正确地重写了你的JOIN,但总的来说它应该是这样的:

WITH jobs_refined AS (
    SELECT
        jobs.*,
        (SELECT CASE WHEN lead_informations.state IS NOT NULL THEN lead_informations.state ELSE 'NEW' END) AS lead_state
    FROM jobs
    LEFT JOIN lead_informations
        ON lead_informations.job_id = jobs.id
        AND lead_informations.mechanic_id = 3
)
SELECT *
FROM jobs_refined
WHERE lead_state = 'NEW'

答案 1 :(得分:19)

您需要在where子句中复制case语句,或者我喜欢执行以下操作:

SELECT *
FROM (
SELECT 
    jobs.*, 
    (CASE WHEN lead_informations.state IS NOT NULL THEN lead_informations.state ELSE 'NEW' END) as lead_state
FROM 
    "jobs"
    LEFT JOIN lead_informations ON lead_informations.job_id = jobs.id
    AND lead_informations.mechanic_id = 3
) q1
WHERE (lead_state = 'NEW')

答案 2 :(得分:14)

正如您所经历的那样,MySQL的支持是非标准的。正确的方法是重新打印SELECT子句中使用的相同表达式:

SELECT
    jobs.*, 
    CASE 
         WHEN lead_informations.state IS NOT NULL THEN lead_informations.state 
         ELSE 'NEW' 
    END AS lead_state
FROM
    jobs
    LEFT JOIN lead_informations ON
        lead_informations.job_id = jobs.id
        AND
        lead_informations.mechanic_id = 3
WHERE
    lead_informations.state IS NULL

答案 3 :(得分:1)

我认为通常的解决方案是使用内部SELECT进行计算(在本例中使用CASE语句),以便在执行到达该查询时,内部SELECT的结果可用于整个外部查询。否则,首先计算WHERE子句,并且对SELECT子句一无所知。

答案 4 :(得分:0)

我在这样的地方使用了别名。 (内部查询)。

Select "Vendors"."VendorId", "Vendors"."Name","Result"."Total" 
From (Select "Trans"."VendorId", ("Trans"."A"+"Trans"."B"+"Trans"."C")    AS "Total"
        FROM "Trans"
    WHERE "Trans"."Year"=2014                                                
    ) As "Result"
JOIN "Vendors" ON "Result"."VendorId"="Vendors"."VendorId" 
WHERE "Vendors"."Class"='I' AND "Result"."Total" > 200

答案 5 :(得分:0)

SELECT "tab_1"."BirthDate", "tab_1"."col_1" FROM (
   SELECT BirthDate, DATEADD(year, 18, BirthDate) AS "col_1" FROM Employees
) AS "tab_1"
WHERE "tab_1"."col_1" >= '2000-12-31';