开发者

Why Can't I Use Defined Variable in Where Clause

开发者 https://www.devze.com 2023-01-24 12:55 出处:网络
My query is: SELECT offer, (SELECT AVG(offer) FR开发者_如何学GoOM project_bids ) as var1 FROM `project_bids`

My query is:

SELECT 
  offer, 
  (SELECT 
        AVG(offer) 
   FR开发者_如何学GoOM 
        project_bids
  ) as var1 
FROM 
  `project_bids` 
WHERE 
  offer > var1

It causes "#1054 - Unknown column 'var1' in 'where clause'" error. Can anybody expalain why gives that error ? (i know working sql but i want to learn why it fails)


The sequence of execution of clauses of a SELECT statement is mentioned here:

http://blog.sqlauthority.com/2007/06/14/sql-server-easy-sequence-of-select-from-join-where-group-by-having-order-by/

Alias of an column can not be used in any clause except the last clause "ORDER BY".


you would have to move "var1" out of the where and put in it to a having statement

the where statement does not have access to columns created in the select statement


Write it as below:

SELECT offer, (SELECT AVG(offer) FROM project_bids) as var1 FROM project_bids WHERE offer > (SELECT AVG(offer) FROM project_bids)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号