Using an Alias column in the where clause in Postgresql

后端 未结 6 1185
轮回少年
轮回少年 2020-11-22 11:04

I have a query like this:

SELECT
    jobs.*, 
    (
        CASE
            WHEN lead_informations.state IS NOT NULL THEN lead_informations.state
                   


        
6条回答
  •  感动是毒
    2020-11-22 11:24

    You would need to either duplicate the case statement in the where clause, or my preference is to do something like the following:

    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')
    

提交回复
热议问题