简体   繁体   中英

“Invalid column name” error in SQL

What's wrong with this code?

I get this error:

Invalid column name 'Distance'

Code:

SELECT 
    Company.CompanyId as Id,
    ( 6371  * acos( cos( radians(47.8423155) ) * cos( radians( Company.Latitude  ) ) * cos( radians( Company.Longitude  ) - radians(35.232933) ) + sin( radians(47.8423155) ) * sin( radians( Company.Latitude ) ) ) ) AS Distance
FROM 
    Company 
INNER JOIN  
    Product ON Company.CompanyId = Product.CompanyId 
WHERE
    Distance< 5000   
ORDER BY
    Distance

Depending on the you're using, some RDBMSs don't allow referring to column aliases in the where and order by columns. Just use the actual column names:

SELECT      Company.CompanyId as Id,
            Company.VisitCount AS myVisitCount 
FROM        Company
INNER JOIN  Product ON  Company.CompanyId = Product.CompanyId 
WHERE       Company.VisitCount < 5000   
ORDER BY    Company.VisitCount

Wrap the select inside subselect

   select * from(SELECT 
    Company.CompanyId as Id,
    ( 6371  * acos( cos( radians(47.8423155) ) * cos( radians( Company.Latitude  ) ) * cos( radians( Company.Longitude  ) - radians(35.232933) ) + sin( radians(47.8423155) ) * sin( radians( Company.Latitude ) ) ) ) AS Distance
FROM 
    Company 
INNER JOIN  
    Product ON (Company.CompanyId = Product.CompanyId) 
) AS P
WHERE
    P.Distance< 5000   
ORDER BY
    P.Distance;

The inner subquery returns the function on basis of which you are filtering with the alias Distance.

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