简体   繁体   中英

PostgreSQL column “enginePower” does not exist

I get this error when I try to use my SELECT AS name.

CREATE VIEW CanDrive AS
    SELECT Car.name,
    (SELECT SUM(engineParts) FROM Engine WHERE Car.engine = Engine.type) AS enginePower,

    CASE WHEN enginePower >= 30 THEN 'yes' ELSE 'no' END AS canDrive

    FROM Car;

Why do I get the error column "enginePower" does not exist when I clearly stated it?

EnginePower is derived and doesn't mean anything yet within the context of that query -- it's just an alias. You could overcome this by evaluating the same expression as above:

   case
     when (SELECT SUM(engineParts) FROM Engine WHERE Car.engine = Engine.type) >= 30
       then 'yes'
     else 'no'
   end as canDrive

Or even better by wrapping it in a common table expression/subquery:

with cte as (
    SELECT
       Car.name,
      (SELECT SUM(engineParts) FROM Engine WHERE Car.engine = Engine.type) AS enginePower
    FROM Car
)
select name, enginePower, case when enginePower >= 30 then 'yes' else 'no' end as canDrive
from cte

Or better yet, perhaps, just convert your scalars into a standard join:

select
  c.name, sum (engineParts) as enginePower,
  case when sum (engineParts) >= 30 then 'yes' else 'no' end as hasPower
from
  car c
  left join engine e on
    c.engine = e.type
group by
  c.name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM